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: 77
💡 Note: The best triplet is (0,2,4): (nums[0] - nums[2]) * nums[4] = (12 - 1) * 7 = 77.
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
Maximum Value of an Ordered Triplet II INPUT nums array: 12 i=0 6 i=1 1 i=2 2 i=3 7 i=4 Triplet Value Formula: (nums[i] - nums[j]) * nums[k] Constraint: i < j < k Optimal Triplet: i=0, j=2, k=4 (12 - 1) * 7 = 77 Find maximum triplet value using single pass ALGORITHM STEPS 1 Initialize Variables maxVal=0, maxDiff=0, maxLeft=nums[0] 2 Track Maximum Left maxLeft = max(maxLeft, nums[i]) 3 Track Maximum Diff maxDiff = max(maxDiff, maxLeft-nums[j]) 4 Update Result maxVal = max(maxVal, maxDiff*nums[k]) Single Pass Tracking: k maxLeft maxDiff maxVal 0 12 0 0 1 12 6 0 2 12 11 6 3 12 11 22 4 12 11 77 FINAL RESULT Maximum Value 77 Optimal Calculation: i=0: nums[0] = 12 j=2: nums[2] = 1 k=4: nums[4] = 7 (12 - 1) * 7 = 11 * 7 = 77 OK - Output: 77 Time: O(n) | Space: O(1) Key Insight: Instead of checking all O(n^3) triplets, we track the maximum value seen to the left (maxLeft) and the maximum difference (maxLeft - nums[j]) as we iterate. For each position k, we simply multiply maxDiff by nums[k] to get the best triplet value ending at k. This greedy approach achieves O(n) time complexity. TutorialsPoint - Maximum Value of an Ordered Triplet II | Greedy - Single Pass Optimization
Asked in
Google 12 Amazon 8 Microsoft 6
8.9K Views
Medium Frequency
~15 min Avg. Time
245 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