2873. Maximum Value of an Ordered Triplet I #1509
-
2873. Maximum Value of an Ordered Triplet I Difficulty: Easy Topics: You are given a 0-indexed integer array Return the maximum value over all triplets of indices The value of a triplet of indices Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum value of all possible ordered triplets (i, j, k) such that i < j < k in a given array. The value of each triplet is calculated as (nums[i] - nums[j]) * nums[k]. If all such triplets have a negative value, we return 0. ApproachThe key insight to optimize the solution is to recognize that for each pair (i, j), the maximum possible value of the triplet (i, j, k) can be determined by the maximum value of nums[k] for k > j. This allows us to precompute the maximum value to the right of each index j, which reduces the problem from O(n^3) time complexity to O(n^2).
Let's implement this solution in PHP: 2873. Maximum Value of an Ordered Triplet I <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function maximumTripletValue($nums) {
$len = count($nums);
if ($len < 3) return 0; // According to constraints, len >=3, but added for safety
$max_right = array_fill(0, $len, 0);
for ($j = $len - 2; $j >= 0; $j--) {
$max_right[$j] = max($nums[$j + 1], $max_right[$j + 1]);
}
$max_val = PHP_INT_MIN;
for ($i = 0; $i < $len - 1; $i++) {
for ($j = $i + 1; $j < $len - 1; $j++) {
$current = ($nums[$i] - $nums[$j]) * $max_right[$j];
if ($current > $max_val) {
$max_val = $current;
}
}
}
return $max_val > 0 ? $max_val : 0;
}
// Test cases
$nums1 = [12,6,1,2,7];
$nums2 = [1,10,3,4,19];
$nums3 = [1,2,3];
echo maximumTripletValue($nums1) . "\n"; // Output: 77
echo maximumTripletValue($nums2) . "\n"; // Output: 133
echo maximumTripletValue($nums3) . "\n"; // Output: 0
?> Explanation:
This approach efficiently reduces the problem complexity by leveraging precomputed values, making it feasible to handle larger input sizes within acceptable time limits. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum value of all possible ordered triplets (i, j, k) such that i < j < k in a given array. The value of each triplet is calculated as (nums[i] - nums[j]) * nums[k]. If all such triplets have a negative value, we return 0.
Approach
The key insight to optimize the solution is to recognize that for each pair (i, j), the maximum possible value of the triplet (i, j, k) can be determined by the maximum value of nums[k] for k > j. This allows us to precompute the maximum value to the right of each index j, which reduces the problem from O(n^3) time complexity to O(n^2).
max_right
where each element at index j is the maximum valu…