Input: nums =[5,6,9]Output: 8Explanation: We only have one choice for an increasing triplet and that ischoosing all three elements. The value of this triplet would be `5 - 6 + 9 =
8`.
Example 2:
1
2
3
4
5
6
7
8
Input: nums =[1,5,3,6]Output: 4Explanation: There are only two increasing triplets:`(0, 1, 3)`: The value of this triplet is`nums[0] - nums[1] + nums[3] = 1 - 5
+ 6 = 2`.`(0, 2, 3)`: The value of this triplet is`nums[0] - nums[2] + nums[3] = 1 - 3
+ 6 = 4`.Thus the answer would be `4`.
Constraints:
3 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
The input is generated such that at least one triplet meets the given condition.
To maximize the value of a triplet (i, j, k) with i < j < k and nums[i] < nums[j] < nums[k], we want to maximize nums[i] - nums[j] + nums[k]. For each j, we can keep track of the minimum nums[i] to the left and the maximum nums[k] to the right, and check if a valid triplet exists.
classSolution {
publicintmaximumTripletValue(int[] nums) {
int n = nums.length, ans = 0;
int[] preMin =newint[n], sufMax =newint[n];
preMin[0]= nums[0];
for (int i = 1; i < n; ++i) preMin[i]= Math.min(preMin[i-1], nums[i]);
sufMax[n-1]= nums[n-1];
for (int i = n-2; i >= 0; --i) sufMax[i]= Math.max(sufMax[i+1], nums[i]);
for (int j = 1; j < n-1; ++j) {
if (preMin[j-1]< nums[j]&& nums[j]< sufMax[j+1]) {
ans = Math.max(ans, preMin[j-1]- nums[j]+ sufMax[j+1]);
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
funmaximumTripletValue(nums: IntArray): Int {
val n = nums.size
val preMin = IntArray(n)
val sufMax = IntArray(n)
preMin[0] = nums[0]
for (i in1 until n) preMin[i] = minOf(preMin[i-1], nums[i])
sufMax[n-1] = nums[n-1]
for (i in n-2 downTo 0) sufMax[i] = maxOf(sufMax[i+1], nums[i])
var ans = 0for (j in1 until n-1) {
if (preMin[j-1] < nums[j] && nums[j] < sufMax[j+1]) {
ans = maxOf(ans, preMin[j-1] - nums[j] + sufMax[j+1])
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaximumTripletValue(self, nums: list[int]) -> int:
n = len(nums)
pre_min = [0] * n
suf_max = [0] * n
pre_min[0] = nums[0]
for i in range(1, n):
pre_min[i] = min(pre_min[i-1], nums[i])
suf_max[-1] = nums[-1]
for i in range(n-2, -1, -1):
suf_max[i] = max(suf_max[i+1], nums[i])
ans =0for j in range(1, n-1):
if pre_min[j-1] < nums[j] < suf_max[j+1]:
ans = max(ans, pre_min[j-1] - nums[j] + suf_max[j+1])
return ans