Running through iterations gives us a tangible sense of how the algorithm works, especially when we start from the end of the array. Let's analyze the iterations on the given example prices = [ 10, 7, 6, 2, 9, 4 ]:
Iteration Overview

Initialization:
maxProfit = 0: the maximum profit found so far.curMax = 4: the current maximum price (initialized with the last price in the array).
Iterative Passes:
1. First Pass ([4]):
- There's only one element, so there's no profit to calculate.
maxProfitremains0,curMaxremains4.
2. Second Pass ([..., 9, 4]):
curMaxis updated to9, as it's greater than the previouscurMax.maxProfitremains0as we have not found a suitable buying price yet.
3. Third Pass ([..., 2, 9, 4]):
- Potential profit is
9 - 2 = 7, somaxProfitis updated to7. curMaxremains9.
4. Fourth Pass ([..., 6, 2, 9, 4]):
- Potential profit is
9 - 6 = 3, but it's less than the currentmaxProfit. maxProfitremains7,curMaxremains9.
5. Fifth Pass ([..., 7, 6, 2, 9, 4]):
- Potential profit is
9 - 7 = 2, but it's less than the currentmaxProfit. maxProfitremains7,curMaxremains9.
Result:
- The maximum profit of
7, achieved by buying at2and selling at9.


