Maximum Increasing Triplet Value - Problem

Maximum Increasing Triplet Value

You are given an integer array nums. Your task is to find three indices i, j, and k such that:

  • i < j < k (indices must be in increasing order)
  • nums[i] < nums[j] < nums[k] (values must form a strictly increasing sequence)
  • The value of the triplet is nums[i] - nums[j] + nums[k]

Return the maximum possible value among all valid triplets. If no such triplet exists, return 0.

Example: For array [1, 5, 3, 6], we can form triplet (0, 1, 3) where 1 < 5 < 6, giving us value 1 - 5 + 6 = 2.

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 5, 3, 6]
โ€บ Output: 4
๐Ÿ’ก Note: The valid increasing triplets are (0,1,3) with value 1-5+6=2 and (0,2,3) with value 1-3+6=4. The maximum is 4.
example_2.py โ€” No Valid Triplet
$ Input: [5, 4, 3, 2, 1]
โ€บ Output: 0
๐Ÿ’ก Note: The array is decreasing, so no increasing triplet exists.
example_3.py โ€” Multiple Triplets
$ Input: [1, 3, 2, 4, 5]
โ€บ Output: 4
๐Ÿ’ก Note: Valid triplets: (0,1,3): 1-3+4=2, (0,1,4): 1-3+5=3, (0,2,3): 1-2+4=3, (0,2,4): 1-2+5=4, (2,3,4): 2-4+5=3. Maximum is 4.

Constraints

  • 3 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค 106
  • All elements in nums are positive integers

Visualization

Tap to expand
Stock Trading Strategy VisualizationBUY$1 (lowest)FEE$3 (transaction)SELL$8 (highest)Profit CalculationBuy Price - Transaction Fee + Sell Price$1 - $3 + $8 = $6Time โ†’Price โ†’Transaction Point(Middle Element)
Understanding the Visualization
1
Choose Transaction Point
Pick a middle point j where you'll pay the transaction fee (nums[j])
2
Find Best Buy Price
Look for the lowest buy price before j (minimum nums[i] where i < j and nums[i] < nums[j])
3
Find Best Sell Price
Look for the highest sell price after j (maximum nums[k] where k > j and nums[k] > nums[j])
4
Calculate Profit
Profit = buy_price - transaction_fee + sell_price = nums[i] - nums[j] + nums[k]
Key Takeaway
๐ŸŽฏ Key Insight: For maximum profit, fix the transaction fee point and find the optimal buy low/sell high boundaries around it.
Asked in
Google 45 Amazon 38 Microsoft 25 Meta 18
48.2K Views
Medium-High Frequency
~25 min Avg. Time
1.5K 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