Maximum Value of an Ordered Triplet I - Problem
You are given a 0-indexed integer array nums.
Return the maximum value over all triplets of indices (i, j, k) such that i < j < k. If all such triplets have a negative value, return 0.
The value of a triplet of indices (i, j, k) is equal to (nums[i] - nums[j]) * nums[k].
Input & Output
Example 1 — Basic Case
$
Input:
nums = [12,6,1,2,7]
›
Output:
77
💡 Note:
The maximum value is achieved at triplet (0,2,4): (12-1)*7 = 11*7 = 77
Example 2 — All Negative
$
Input:
nums = [1,10,3,4,19]
›
Output:
133
💡 Note:
Maximum triplet is (0,2,4): (1-3)*19 = -2*19 = -38, but (1,2,4): (10-3)*19 = 7*19 = 133
Example 3 — Small Array
$
Input:
nums = [1,2,3]
›
Output:
0
💡 Note:
Only one triplet (0,1,2): (1-2)*3 = -1*3 = -3, which is negative, so return 0
Constraints
- 3 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array: [12, 6, 1, 2, 7]
2
Process
Find triplet (i,j,k) that maximizes (nums[i] - nums[j]) * nums[k]
3
Output
Maximum value: 77 from triplet (0,2,4)
Key Takeaway
🎯 Key Insight: For each k, efficiently track the maximum difference (nums[i] - nums[j]) seen so far
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code