Input: nums =[12,6,1,2,7]Output: 77Explanation: 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:
1
2
3
4
Input: nums =[1,10,3,4,19]Output: 133Explanation: 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:
1
2
3
Input: nums =[1,2,3]Output: 0Explanation: 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.
To solve the problem efficiently, the objective is to calculate the maximum value of (nums[i] - nums[j]) * nums[k] for all triplets that satisfy the condition i < j < k. If all such triplet values are negative, the result should be 0.
Iterate over the array with three nested loops: the outer loop for i, the middle loop for j, and the inner loop for k. Ensure the conditions i < j < k are satisfied.
For each valid triplet (i, j, k), compute the value: (nums[i] - nums[j]) * nums[k].
Keep track of the maximum value encountered (ans).
If the maximum value (ans) is negative after evaluating all triplets, return 0; otherwise, return ans.
classSolution {
publiclongmaximumTripletValue(int[] nums) {
long ans = Long.MIN_VALUE; // Use `long` since the return type is `long`int n = nums.length; // Store the length of the array// Iterate over triplets respecting i < j < kfor (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
// Calculate the value of the tripletlong val = (long) (nums[i]- nums[j]) * nums[k];
// Update the maximum value ans = Math.max(ans, val);
}
}
}
// Return the result or 0 if the maximum value is negativereturn Math.max(ans, 0);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defmaximumTripletValue(self, nums: List[int]) -> int:
ans: int = float('-inf')
n: int = len(nums)
# Iterate over triplets respecting i < j < kfor i in range(n -2):
for j in range(i +1, n -1):
for k in range(j +1, n):
# Calculate the value of the triplet val: int = (nums[i] - nums[j]) * nums[k]
# Update the maximum value ans = max(ans, val)
# Return the result or 0 if negativereturn max(ans, 0)