To solve this problem, we need to find the best possible pair of days to buy and then sell a stock to maximize our profit. But we are allowed to do this only once — that is, we can make one buy and one sell, and the buy must happen before the sell.
The trick is to look at the prices and figure out how low we can buy and how high we can sell after that buy. So, we keep track of the minimum price
we’ve seen so far while scanning the array, and at each step, we check if selling at the current price would give us more profit than what we’ve recorded before.
Understanding Through Cases
- Case 1: Profitable Transaction Exists
If the prices go up after some point, we can buy at the low point and sell at the high point. For example, in [7, 1, 5, 3, 6, 4], we buy at 1 and sell at 6 to gain a profit of 5.
- Case 2: Prices Only Go Down
If the prices keep decreasing (like [7, 6, 4, 3, 1]), then no matter where we buy and sell, we’ll always lose money. In such cases, the best we can do is avoid any transaction, and the answer is 0.
- Case 3: Constant or Increasing Trend
When prices steadily increase (like [1, 2, 3, 4, 5]), we can buy at the very beginning and sell at the end. This gives us the highest possible profit in the trend.
- Case 4: Only One Price
If the array has only one price, we cannot sell after buying, so no profit can be made. Hence, the answer is 0.
- Case 5: Empty Input
If the prices array is empty, there is no transaction possible at all. So, we return 0.
This method works efficiently because we only need to pass through the array once while tracking the lowest price seen so far and the best profit we can get. That gives us a time complexity of O(n), which is optimal for this problem.