Maximum Value of an Ordered Triplet I — Medium Problem & Solution
The value of an ordered triplet (i, j, k) with i < j < k is (nums[i] - nums[j]) * nums[k].
- Difficulty: Medium
- Topics: Arrays, Math, Prefix Sum
- Asked at: Amazon, Google, Uber
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
The value of an ordered triplet (i, j, k) with i < j < k is (nums[i] - nums[j]) * nums[k].
Return the maximum value over all such triplets, or 0 if every triplet has a negative value.
Example 1
Input: nums = [12,6,1,2,7]
Output: 77
Explanation: (12 - 1) * 7 = 77.
Example 2
Input: nums = [1,10,3,4,19]
Output: 133
Explanation: (1 - 10) is negative; (10 - 3) * 19 = 133.
Example 3
Input: nums = [1,2,3]
Output: 0
Explanation: The only triplet gives (1 - 2) * 3 = -3, so the answer floors at 0.
Constraints
3 <= nums.length <= 10001 <= nums[i] <= 1000000
How to solve Maximum Value of an Ordered Triplet I
Sweep k from left to right while maintaining two running maxima: the largest element seen so far, and the largest difference nums[i] - nums[j] over pairs entirely before k. Then each k is answered in constant time.
Approach
- Keep
bestI(the maximum element seen),bestDiff(the maximumnums[i] - nums[j]withi < j), andbest(the answer, starting at 0). - At index
k, first updatebestwithbestDiff * nums[k]. - Then update
bestDiffwithbestI - nums[k], and finallybestIwithnums[k].
Why it works
The update order is what enforces i < j < k: bestDiff is read before it is allowed to include index k as a j, and bestI is updated last so it never contributes an i at or after the j that uses it.
Complexity
- Time —
O(n) - Space —
O(1)
Pitfalls
- Updating
bestIbeforebestDiffletsiandjbe the same index. - Updating
bestDiffbefore reading it letsjequalk. - The answer floors at 0, so it must start at 0 rather than at negative infinity.
Reference solution
Python
from typing import List
def maximumTripletValue(nums: List[int]) -> int:
best = best_diff = best_i = 0
for x in nums:
best = max(best, best_diff * x)
best_diff = max(best_diff, best_i - x)
best_i = max(best_i, x)
return bestJavaScript
var maximumTripletValue = function(nums) {
var best = 0, bestDiff = 0, bestI = 0;
for (var k = 0; k < nums.length; k++) {
if (bestDiff * nums[k] > best) best = bestDiff * nums[k];
if (bestI - nums[k] > bestDiff) bestDiff = bestI - nums[k];
if (nums[k] > bestI) bestI = nums[k];
}
return best;
};Also on the editorial tab: C, C#, C++, Go, Java, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.