Maximum Difference Between Increasing Elements (LeetCode 2016): Solution and Explanation

Easy
Array

Find the biggest rise nums[j] - nums[i] where the smaller value comes first and is strictly smaller. If the array never rises, return -1.

Intuition

Think of the array as a price chart. You want to buy at some point and sell later at a strictly higher price, earning as much as possible.

Fix the selling day j. The best buying day is simply the lowest price before j. So while walking left to right, you only need to remember one number: the lowest value seen so far.

At each new element, either it is above that low, and the rise is a candidate answer, or it is not, and it becomes the new low for everything after it.

Approach: Running minimum

  1. Set best = -1 and low = nums[0].
  2. For every later element x: if x > low, set best = max(best, x - low).
  3. Otherwise (x <= low), set low = x.
  4. Return best.

Step-by-step example

nums = [7,1,5,4]
  1. low = 7, best = -1.
  2. x = 1 is not above 7, so low becomes 1.
  3. x = 5 is above 1. The rise 5 - 1 = 4 beats -1, so best = 4.
  4. x = 4 is above 1, but 4 - 1 = 3 does not beat 4.
  5. Return 4.

Code: Python, Java, C++

1class Solution:
2    def maximumDifference(self, nums: List[int]) -> int:
3        best = -1
4        low = nums[0]
5        for x in nums[1:]:
6            if x > low:
7                best = max(best, x - low)
8            else:
9                low = x
10        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One comparison and at most one update per element.

Space

O(1)

Only low and best are stored.

Other approaches

Check every pair (time O(n^2), space O(1))

Two nested loops over i < j, keeping the largest nums[j] - nums[i] with nums[i] < nums[j]. Fine for n <= 1000 but does far more work.

Prefix minimum array (time O(n), space O(n))

Precompute the minimum of every prefix, then compare each element with the prefix before it. Same idea with an extra array.

Common mistakes

  • Counting equal values. nums[i] < nums[j] is strict, so [5,5] returns -1, not 0.
  • Starting best at 0 instead of -1. A falling array would then wrongly return 0.
  • Updating low before computing the difference with the same element, which gives a rise of 0 against itself.

Frequently asked questions

How is this related to Best Time to Buy and Sell Stock?

It is the same scan. The only change is the empty case: the stock problem returns 0 when no profit exists, this one returns -1, and equal values do not count as a rise.

Why is the smallest earlier value always the best partner?

For a fixed nums[j], the difference nums[j] - nums[i] grows as nums[i] shrinks. Any earlier value larger than the minimum can only give a smaller rise.

Can the answer overflow?

No. Values are between 1 and 10^9, so a difference is below 10^9 and fits in a 32-bit int.