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 Elements INPUT nums = [7, 1, 5, 4, 6] 7 i=0 1 i=1 5 i=2 4 i=3 6 i=4 Goal: Find max(nums[j] - nums[i]) where i < j and nums[i] < nums[j] Constraints: 0 <= i < j < n nums[i] < nums[j] Valid pairs: (1,5), (1,4), (1,6) (5,6), (4,6) Best: 6 - 1 = 5 ALGORITHM STEPS 1 Initialize minVal = nums[0] = 7 maxDiff = -1 2 Iterate from i=1 For each element... 3 Update Logic If nums[i] > minVal: maxDiff = max(maxDiff, nums[i] - minVal) Else: minVal = nums[i] 4 Trace Execution i=1: num=1 < 7, minVal=1 i=2: num=5 > 1, diff=4 i=3: num=4 > 1, diff=3 i=4: num=6 > 1, diff=5 minVal stays 1 throughout maxDiff = 5 FINAL RESULT Optimal pair found: 7 1 min 5 4 6 max 6 - 1 = 5 Output: 5 OK - Valid Solution i=1 < j=4 nums[1]=1 < nums[4]=6 Time: O(n) | Space: O(1) Single pass optimal Key Insight: Track the minimum value seen so far as we iterate. For each new element, if it's greater than the minimum, calculate the difference and update maxDiff. If it's smaller, update the minimum. This ensures we always consider pairs where i < j (since min is from earlier index) and find the maximum difference in O(n) time. TutorialsPoint - Maximum Difference Between Increasing Elements | Single Pass Optimization
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