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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code