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.
maxProfit
remains0
,curMax
remains4
.
2. Second Pass ([..., 9, 4]
):
curMax
is updated to9
, as it's greater than the previouscurMax
.maxProfit
remains0
as we have not found a suitable buying price yet.
3. Third Pass ([..., 2, 9, 4]
):
- Potential profit is
9 - 2 = 7
, somaxProfit
is updated to7
. curMax
remains9
.
4. Fourth Pass ([..., 6, 2, 9, 4]
):
- Potential profit is
9 - 6 = 3
, but it's less than the currentmaxProfit
. maxProfit
remains7
,curMax
remains9
.
5. Fifth Pass ([..., 7, 6, 2, 9, 4]
):
- Potential profit is
9 - 7 = 2
, but it's less than the currentmaxProfit
. maxProfit
remains7
,curMax
remains9
.
Result:
- The maximum profit of
7
, achieved by buying at2
and selling at9
.