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 (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
Maximum Value of an Ordered Triplet I INPUT nums array (0-indexed) 12 i=0 6 i=1 1 i=2 2 i=3 7 i=4 Triplet (i, j, k) where i < j < k Value = (nums[i] - nums[j]) * nums[k] Optimal Triplet: i=0, j=2, k=4 (12 - 1) * 7 = 77 Goal: Find maximum value over all valid triplets ALGORITHM STEPS 1 Initialize Trackers maxVal=0, maxDiff=0, maxI=0 2 Iterate k from 0 to n-1 Each k is potential third index 3 Update maxVal maxVal = max(maxVal, maxDiff*nums[k]) 4 Update Trackers maxDiff = max(maxDiff, maxI-nums[k]) maxI = max(maxI, nums[k]) State at each k: k=0: maxI=12, maxDiff=0, maxVal=0 k=1: maxI=12, maxDiff=6, maxVal=0 k=2: maxI=12, maxDiff=11, maxVal=6 k=3: maxI=12, maxDiff=11, maxVal=22 k=4: maxI=12, maxDiff=11, maxVal=77 FINAL RESULT Maximum Value 77 Winning Triplet 12 i=0 1 j=2 7 k=4 Calculation: (nums[0] - nums[2]) * nums[4] = (12 - 1) * 7 = 11 * 7 = 77 OK - Maximum found! Key Insight: Track Maximum Difference Optimization Instead of O(n^3) brute force, we achieve O(n) by tracking: 1) maxI = maximum nums[i] seen so far, 2) maxDiff = maximum (nums[i] - nums[j]) for valid i < j pairs. At each k, we compute maxDiff * nums[k] and update our trackers. This works because we only need the BEST previous difference, not all pairs. TutorialsPoint - Maximum Value of an Ordered Triplet I | Optimized - Track Maximum Difference
Asked in
Amazon 15 Microsoft 12
12.0K 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