Skip to content

1014. Best Sightseeing Pair #1006

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

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 score values[i] + values[j] + i - j for every valid pair (i, j).

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 …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Dec 27, 2024
Collaborator

@mah-shamim
Comment options

mah-shamim Dec 27, 2024
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested medium Difficulty
2 participants