Maximum Difference Between Increasing Elements - Problem
Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
Return the maximum difference. If no such i and j exists, return -1.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [7,1,5,4,6]
›
Output:
5
💡 Note:
The maximum difference is 6 - 1 = 5, where i = 1 and j = 4 (nums[1] = 1, nums[4] = 6)
Example 2 — No Valid Pair
$
Input:
nums = [9,4,3,2]
›
Output:
-1
💡 Note:
No valid pair exists since the array is in decreasing order, so no i < j with nums[i] < nums[j]
Example 3 — Small Difference
$
Input:
nums = [1,5,2,10]
›
Output:
9
💡 Note:
Maximum difference is 10 - 1 = 9, where i = 0 and j = 3
Constraints
- 1 ≤ nums.length ≤ 1000
- 1 ≤ nums[i] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of integers [7,1,5,4,6]
2
Process
Find pairs (i,j) where i < j and nums[i] < nums[j], calculate differences
3
Output
Return maximum difference: 5 (from 6 - 1)
Key Takeaway
🎯 Key Insight: Track the minimum element seen so far to maximize the difference with future elements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code