Maximum Increasing Triplet Value - Problem

Given an integer array nums, return the maximum value of a triplet (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k].

The value of a triplet (i, j, k) is defined as nums[i] - nums[j] + nums[k].

If no such triplet exists, return 0.

Input & Output

Example 1 — Basic Increasing Triplet
$ Input: nums = [2,1,3,4]
Output: 5
💡 Note: The optimal triplet is at indices (1,2,3) with values (1,3,4). Since 1 < 3 < 4, the triplet value is 1 - 3 + 4 = 2. However, we can also use (0,1,3) giving 2 - 1 + 4 = 5, which is maximum.
Example 2 — Multiple Valid Triplets
$ Input: nums = [1,2,3,4,5]
Output: 4
💡 Note: Multiple triplets exist. The best is (0,1,4) with values (1,2,5), giving 1 - 2 + 5 = 4. Any triplet (i,j,k) with i < j < k works since array is strictly increasing.
Example 3 — No Valid Triplet
$ Input: nums = [5,4,3,2,1]
Output: 0
💡 Note: Array is decreasing, so no triplet (i,j,k) exists where nums[i] < nums[j] < nums[k]. Return 0.

Constraints

  • 3 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Maximum Increasing Triplet Value ProblemFind triplet (i,j,k) with i < j < k and nums[i] < nums[j] < nums[k]2134i=0i=1i=2i=3Valid triplets and their values:Triplet (0,1,3): nums[0] - nums[1] + nums[3] = 2 - 1 + 4 = 5Triplet (0,2,3): nums[0] - nums[2] + nums[3] = 2 - 3 + 4 = 3Triplet (1,2,3): nums[1] - nums[2] + nums[3] = 1 - 3 + 4 = 2Maximum Value: 5
Understanding the Visualization
1
Input Array
Array [2,1,3,4] with indices 0,1,2,3
2
Find Valid Triplets
Check all i<j<k where nums[i]<nums[j]<nums[k]
3
Calculate Values
Compute nums[i]-nums[j]+nums[k] for each valid triplet
Key Takeaway
🎯 Key Insight: Maximize the first and last elements while minimizing the middle element in the triplet formula
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
847 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