2874. Maximum Value of an Ordered Triplet II #1513
-
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:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum value of the triplet (i, j, k) such that i < j < k and the value is computed as (nums[i] - nums[j]) * nums[k]. If all such triplets have a negative value, we return 0. Approach
Let's implement this solution in PHP: 2874. Maximum Value of an Ordered Triplet II <?php
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer[]
*/
function twoSum($nums, $target) {
// Create an associative array (hash map) to store numbers and their indices
$map = [];
// Iterate through the array
foreach ($nums as $index => $num) {
// Calculate the complement of the current number
$complement = $target - $num;
// Check if the complement exists in the map
if (isset($map[$complement])) {
// If found, return the indices of the complement and the current number
return [$map[$complement], $index];
}
// Otherwise, add the current number and its index to the map
$map[$num] = $index;
}
// If no solution is found (although the problem guarantees one), return an empty array
return [];
}
// Test cases
$nums1 = [12,6,1,2,7];
echo maxTripletValue($nums1) . "\n"; // Output: 77
$nums2 = [1,10,3,4,19];
echo maxTripletValue($nums2) . "\n"; // Output: 133
$nums3 = [1,2,3];
echo maxTripletValue($nums3) . "\n"; // Output: 0
?> Explanation:
This approach ensures that we efficiently compute the required values in O(n) time and space complexity, making it suitable for large input arrays. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum value of the triplet (i, j, k) such that i < j < k and the value is computed as (nums[i] - nums[j]) * nums[k]. If all such triplets have a negative value, we return 0.
Approach
Precompute Maximum Values:
Iterate Over Possible j Values:
Track Maximum Value: