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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code