2873. Maximum Value of an Ordered Triplet I
Description
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 <= 100
1 <= nums[i] <= 106
Solutions
Solution 1: Maintaining Prefix Maximum and Maximum Difference
We use two variables \(\textit{mx}\) and \(\textit{mxDiff}\) to maintain the prefix maximum value and maximum difference, respectively, and use a variable \(\textit{ans}\) to maintain the answer. Initially, these variables are all \(0\).
Next, we iterate through each element \(x\) in the array as \(\textit{nums}[k]\). First, we update the answer \(\textit{ans} = \max(\textit{ans}, \textit{mxDiff} \times x)\). Then we update the maximum difference \(\textit{mxDiff} = \max(\textit{mxDiff}, \textit{mx} - x)\). Finally, we update the prefix maximum value \(\textit{mx} = \max(\textit{mx}, x)\).
After iterating through all elements, we return the answer \(\textit{ans}\).
The time complexity is \(O(n)\), where \(n\) is the length of the array. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|