Maximum Value of an Ordered Triplet II Problem
Description
LeetCode Problem 2874.
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].
Example 1:
Input: nums = [12,6,1,2,7]
Output: 77
Explanation: The value of the triplet (0, 2, 4) is (nums[0] - nums[2]) * nums[4] = 77.
It can be shown that there are no ordered triplets of indices with a value greater than 77.
Example 2:
Input: nums = [1,10,3,4,19]
Output: 133
Explanation: The value of the triplet (1, 2, 4) is (nums[1] - nums[2]) * nums[4] = 133.
It can be shown that there are no ordered triplets of indices with a value greater than 133.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation: The only ordered triplet of indices (0, 1, 2) has a negative value of (nums[0] - nums[1]) * nums[2] = -3. Hence, the answer would be 0.
Constraints:
3 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Prefix Maximum and Maximum Difference
Keep three values while scanning left to right: mx, the largest earlier element, and mxDiff, the largest nums[i] - nums[j] seen so far (i < j), plus the answer ans. All start at 0.
For each element x, treated as nums[k]: first update ans = max(ans, mxDiff * x), then mxDiff = max(mxDiff, mx - x), then mx = max(mx, x). The order matters, so each value only uses elements before x. A negative value is never kept, which handles the case where every triplet is negative.
Complexity: time O(n), space O(1), where n is the length of the array.
class Solution:
def maximumTripletValue(self, nums: List[int]) -> int:
ans = mx = mx_diff = 0
for x in nums:
ans = max(ans, mx_diff * x)
mx_diff = max(mx_diff, mx - x)
mx = max(mx, x)
return ans