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.
classSolution {
publiclongmaximumTripletValue(int[] nums) {
int n = nums.length;
long ans = 0;
// Track the maximum value of nums[i] while traversingint max_i = nums[0];
// Iterate through the array to find the maximum value of the tripletfor (int j = 1; j < n - 1; j++) { // `j` must be the second element, avoiding edges// Find max `nums[k]` from `(j + 1) to (n - 1)`int max_k = nums[j + 1];
for (int k = j + 2; k < n; k++) {
max_k = Math.max(max_k, nums[k]);
}
// Compute the triplet value using precomputed valueslong triplet_val = (long) (max_i - nums[j]) * max_k;
// Update the maximum triplet value ans = Math.max(ans, triplet_val);
// Update the running maximum for `nums[i]` max_i = Math.max(max_i, nums[j]);
}
return ans;
}
}
classSolution:
defmaximumTripletValue(self, nums: List[int]) -> int:
n: int = len(nums)
ans: int =0# Track the maximum value of nums[i] while traversing max_i: int = nums[0]
# Iterate through the array to find the maximum value of the tripletfor j in range(1, n -1): # `j` must be the second element, avoiding edges max_k: int = max(nums[j +1:]) # Find max `nums[k]` from `(j + 1) to (n - 1)`# Compute the triplet value using precomputed values triplet_val: int = (max_i - nums[j]) * max_k
# Update the maximum triplet value ans = max(ans, triplet_val)
# Update the running maximum for `nums[i]` max_i = max(max_i, nums[j])
return ans
To achieve an O(n) solution, we need to optimise the tracking and calculation of values such that we do not perform repetitive work for precomputations like maximum values. The key idea here is to make use of prefix maximums for nums[i] and suffix maximums for nums[k] in a single traversal.
classSolution:
defmaximumTripletValue(self, nums: List[int]) -> int:
n: int = len(nums)
if n <3:
return0# Need at least 3 elements for a valid triplet# Step 1: Compute prefix maximums prefix_max = [0] * n
prefix_max[0] = nums[0]
for i in range(1, n):
prefix_max[i] = max(prefix_max[i -1], nums[i])
# Step 2: Compute suffix maximums suffix_max = [0] * n
suffix_max[n -1] = nums[n -1]
for i in range(n -2, -1, -1):
suffix_max[i] = max(suffix_max[i +1], nums[i])
# Step 3: Calculate maximum triplet value ans: int =0for j in range(1, n -1): # 'j' must be the middle element triplet_val: int = (prefix_max[j -1] - nums[j]) * suffix_max[j +1]
ans = max(ans, triplet_val)
return ans