You are given an integer array prices where prices[i] is the price of a given stock on the ith day.
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Explanation:
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4. Total profit is 4.
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.
The problem is essentially about finding opportunities to make as much profit as possible by buying stocks on one day and selling them on another. This can be achieved by making transactions whenever there's a profit to be made, without concern for a future decrement in prices.
In a simplified manner, the problem reduces to accumulating all positive differences between consecutive days. By always projecting into the future and accumulating possible gains daily, we capitalize on every rising curve of the stock price graph.
Another way to look at this problem is to find every consecutive pair of peaks and valleys. A peak-to-valley traversal adds the difference from each peak to its preceding valley to determine the overall profit through multiple transactions.
This approach mimics the real-world scenario of buying stock at valleys (local minimums) and selling it at peaks (local maximums). This enables capturing every increasing sequence even if the overall curve spans over several days.