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
Maximum Difference Between Increasing ElementsInput Array:71546i=0i=1i=2i=3i=4Maximum Difference PairFind i < j where nums[i] < nums[j]Calculate nums[j] - nums[i] for maximum differenceResult5
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
Asked in
Amazon 15 Microsoft 12 Google 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 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