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: 3
💡 Note: The optimal triplet is at indices (0,2,3) with values (2,3,4). Since 2 < 3 < 4, the triplet value is 2 - 3 + 4 = 3.
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 INPUT nums = [2, 1, 3, 4] 2 i=0 1 i=1 3 i=2 4 i=3 Find triplet (i, j, k): i < j < k nums[i] < nums[j] < nums[k] Value Formula: nums[i] - nums[j] + nums[k] Valid Triplets: (0,2,3): 2-3+4 = 3 (1,2,3): 1-3+4 = 2 (0,1,3): Invalid (1 not < 3) ALGORITHM STEPS 1 Initialize Tracking Track max left values for each position 2 Single Pass Scan For each j, find best i where nums[i] < nums[j] 3 Find Optimal k For each j, scan right for max nums[k] > nums[j] 4 Calculate Maximum Update max value for each valid triplet Optimization Trick: Precompute max suffix array for nums[k] values to avoid O(n^2) inner loop FINAL RESULT Optimal Triplet Found: 2 i=0 3 j=2 4 k=3 Calculation: nums[0] - nums[2] + nums[3] = 2 - 3 + 4 Output: 5 [OK] Maximum value found! Triplet (0,2,3) is optimal Key Insight: The triplet value formula nums[i] - nums[j] + nums[k] is maximized when nums[i] is maximum among valid left elements, nums[j] is minimum valid middle, and nums[k] is maximum valid right element. Precompute suffix max arrays to achieve O(n) time complexity using single pass optimization. TutorialsPoint - Maximum Increasing Triplet Value | Single Pass Optimization Approach
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