Maximum Difference Between Increasing Elements - Problem

Imagine you're a day trader looking at stock prices throughout a trading day. You have an array of stock prices where each element represents the price at a specific time, and you want to find the maximum profit you can make by buying at one time and selling at a later time.

Given a 0-indexed integer array nums of size n, find the maximum difference between nums[j] - nums[i] such that:

  • 0 โ‰ค i < j < n (you must buy before you sell)
  • nums[i] < nums[j] (you can only profit if the price increases)

Return the maximum difference. If no profitable trade exists, return -1.

Example: For prices [7, 1, 5, 3, 6, 4], buying at price 1 and selling at price 6 gives maximum profit of 5.

Input & Output

example_1.py โ€” Basic Increasing Array
$ Input: nums = [7, 1, 5, 3, 6, 4]
โ€บ Output: 5
๐Ÿ’ก Note: Buy at price 1 (index 1) and sell at price 6 (index 4) for maximum profit of 6 - 1 = 5
example_2.py โ€” No Profit Possible
$ Input: nums = [9, 4, 3, 2]
โ€บ Output: -1
๐Ÿ’ก Note: Array is strictly decreasing, so no valid i < j exists where nums[i] < nums[j]
example_3.py โ€” Small Difference
$ Input: nums = [1, 5, 2, 10]
โ€บ Output: 9
๐Ÿ’ก Note: Buy at price 1 (index 0) and sell at price 10 (index 3) for maximum profit of 10 - 1 = 9

Constraints

  • n == nums.length
  • 2 โ‰ค n โ‰ค 1000
  • 1 โ‰ค nums[i] โ‰ค 109
  • Must have i < j and nums[i] < nums[j]

Visualization

Tap to expand
Stock Trading Strategy VisualizationStock Prices Over Time: [7, 1, 5, 3, 6, 4]PriceTime71 (BUY)536 (SELL)4Maximum Profit: 6 - 1 = 5Best Buy PointBest Sell PointOther Prices๐ŸŽฏ Key Insight: Always buy at the lowest price seen so far!
Understanding the Visualization
1
Track Minimum
Keep track of the lowest stock price seen so far (best buying opportunity)
2
Calculate Profit
For each new price, calculate potential profit if we sell now
3
Update Maximum
Keep track of the highest profit possible
Key Takeaway
๐ŸŽฏ Key Insight: For any selling day, the optimal buying day is always the day with the lowest price encountered so far. This allows us to solve the problem in a single pass with O(n) time complexity.
Asked in
Amazon 42 Google 38 Microsoft 31 Meta 27
89.6K Views
High Frequency
~12 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen