Mark As Completed Discussion

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

Step Eight

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 remains 0, curMax remains 4.

2. Second Pass ([..., 9, 4]):

  • curMax is updated to 9, as it's greater than the previous curMax.
  • maxProfit remains 0 as we have not found a suitable buying price yet.

3. Third Pass ([..., 2, 9, 4]):

  • Potential profit is 9 - 2 = 7, so maxProfit is updated to 7.
  • curMax remains 9.

4. Fourth Pass ([..., 6, 2, 9, 4]):

  • Potential profit is 9 - 6 = 3, but it's less than the current maxProfit.
  • maxProfit remains 7, curMax remains 9.

5. Fifth Pass ([..., 7, 6, 2, 9, 4]):

  • Potential profit is 9 - 7 = 2, but it's less than the current maxProfit.
  • maxProfit remains 7, curMax remains 9.

Result:

  • The maximum profit of 7, achieved by buying at 2 and selling at 9.