1014. Best Sightseeing Pair #1006
-
Topics: You are given an integer array The score of a pair ( Return the maximum score of a pair of sightseeing spots. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use a single-pass approach with a linear time complexity O(n). The idea is to keep track of the best possible Let's implement this solution in PHP: 1014. Best Sightseeing Pair <?php
/**
* @param Integer[] $values
* @return Integer
*/
function maxScoreSightseeingPair($values) {
$maxScore = 0;
$maxI = $values[0]; // Track the maximum values[i] + i
for ($j = 1; $j < count($values); $j++) {
// Calculate the score for the current pair
$maxScore = max($maxScore, $maxI + $values[$j] - $j);
// Update maxI to track the best values[i] + i for the next iteration
$maxI = max($maxI, $values[$j] + $j);
}
return $maxScore;
}
// Example usage:
$values1 = [8, 1, 5, 2, 6];
echo maxScoreSightseeingPair($values1); // Output: 11
$values2 = [1, 2];
echo maxScoreSightseeingPair($values2); // Output: 2
?> Explanation:
Complexity:
This solution efficiently computes the maximum score while adhering to the constraints and is optimized for large inputs. |
Beta Was this translation helpful? Give feedback.
We can use a single-pass approach with a linear time complexity O(n). The idea is to keep track of the best possible
values[i] + i
as we iterate through the array. This allows us to maximize the scorevalues[i] + values[j] + i - j
for every valid pair(i, j)
.Let's implement this solution in PHP: 1014. Best Sightseeing Pair