Best Sightseeing Pair (LeetCode 1014): Solution and Explanation

Medium
Array
Dynamic Programming

Each sightseeing spot has a rating, and visiting spots i < j scores values[i] + values[j] minus the distance j - i. Find the highest score any pair can reach.

Intuition

Trying every pair is O(n^2), which is 1.25 billion pairs at the upper limit. We need to avoid pairing each right end with every left end.

Rewrite the score as (values[i] + i) + (values[j] - j). The distance penalty has been split between the two spots, and now each part depends on only one index.

For a fixed right end j, the second part is fixed, so the best partner is simply the earlier spot with the largest values[i] + i. Another way to see it: a left spot's value fades by 1 for every step you walk away from it, and we want the spot that still looks the brightest from j.

As j moves right, the set of possible left ends only grows by one spot, so a running maximum is enough. This is the same trick as Best Time to Buy and Sell Stock, with an index bonus.

Approach: Running maximum of values[i] + i

  1. Set best_i = values[0] + 0 and best = 0.
  2. For j from 1 to n - 1, compute the candidate best_i + values[j] - j and keep the larger of it and best.
  3. After scoring j, let it compete as a future left end: best_i = max(best_i, values[j] + j).
  4. Return best once every spot has been the right end.

Step-by-step example

values = [8, 1, 5, 2, 6]
  1. best_i = 8 + 0 = 8, best = 0.
  2. j = 1: candidate 8 + 1 - 1 = 8, best = 8. Spot 1 offers 1 + 1 = 2, so best_i stays 8.
  3. j = 2: candidate 8 + 5 - 2 = 11, best = 11. Spot 2 offers 5 + 2 = 7, best_i stays 8.
  4. j = 3: candidate 8 + 2 - 3 = 7, best stays 11. Spot 3 offers 5, best_i stays 8.
  5. j = 4: candidate 8 + 6 - 4 = 10, best stays 11. The answer is 11, from the pair (0, 2).

Code: Python, Java, C++

1class Solution:
2    def maxScoreSightseeingPair(self, values: List[int]) -> int:
3        best = 0
4        best_i = values[0]
5        for j in range(1, len(values)):
6            best = max(best, best_i + values[j] - j)
7            best_i = max(best_i, values[j] + j)
8        return best
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each spot is visited once and does two constant-time max operations.

Space

O(1)

Only best and best_i are stored.

Other approaches

Check every pair (time O(n^2), space O(1))

Two nested loops compute the score of every i < j. It is correct and easy to write but far too slow for 5 * 10^4 spots.

Prefix maximum array (time O(n), space O(n))

Precompute left[j] = max(values[i] + i for i < j) in one pass, then take the maximum of left[j] + values[j] - j in a second pass. It is the same idea with an extra O(n) array.

Common mistakes

  • Updating best_i before scoring j, which lets a spot pair with itself and returns 2 * values[j].
  • Keeping the largest values[i] instead of the largest values[i] + i. A big rating far to the left can lose to a smaller one nearby.
  • Starting the loop at j = 0, which again pairs a spot with itself.
  • Initialising best to values[0] instead of evaluating a real pair; with two spots this can return a score that no pair has.

Frequently asked questions

Why add i to values[i]?

The penalty is j - i, which is -j + i. The +i part belongs to the left spot and the -j part to the right spot, so moving i into the left term makes each half depend on a single index.

Is this really dynamic programming?

It is the smallest form of it: best_i is the answer to the subproblem 'best left end among the first j spots', and each step extends it by one spot in O(1).

Can the best pair be two neighbours?

Yes. If two adjacent spots have the highest ratings, the distance cost is only 1, so they often win. The running maximum handles that case naturally.