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
Maximum Value of Ordered Triplet IIFind max((nums[i] - nums[j]) * nums[k]) where i < j < kInput Array:126127i=0j=123k=4Best Triplet Found:(nums[0] - nums[1]) × nums[4]= (12 - 6) × 7= 6 × 7= 42
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]
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