Maximum Value of an Ordered Triplet II - 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:
42
💡 Note:
The triplet (0,2,4) gives us (nums[0] - nums[2]) * nums[4] = (12 - 1) * 7 = 77. However, we need i < j < k, so we check (0,1,4): (12 - 6) * 7 = 42, which is the maximum.
Example 2 — All Negative Results
$
Input:
nums = [1,10,3,4,19]
›
Output:
133
💡 Note:
The best triplet is (1,2,4): (nums[1] - nums[2]) * nums[4] = (10 - 3) * 19 = 133.
Example 3 — Return Zero Case
$
Input:
nums = [1,2,3]
›
Output:
0
💡 Note:
The only triplet is (0,1,2): (1 - 2) * 3 = -3, which is negative, so we 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] with indices 0,1,2,3,4
2
Process
Check all valid triplets (i,j,k) where i < j < k
3
Output
Maximum value found: (12-6)*7 = 42
Key Takeaway
🎯 Key Insight: Track the maximum difference (nums[i] - nums[j]) while scanning, then multiply by each nums[k]
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code