Added memoization, works for large testcases