I honestly didn’t expect to solve this one on my own, and the process was quite a journey. Persistence pays off!
The problem is roughly: you are trading stocks and can only make one transaction (buy once, sell once). On which day should you buy and on which later day should you sell to maximize profit?
I thought this would be easy – just brute force it. Of course, that resulted in TLE.
Then I racked my brain trying to figure out how to reduce the time complexity. Sorting? Greedy? It felt similar to the 2Sum problem, especially after drawing vertical lines on a graph.
Then it hit me: the difference between consecutive days represents the price change. If I compute these differences and then find the maximum contiguous subarray sum, the problem is solved!
I gave it a try and – AC!
Here is the code:
| |