Best Sightseeing Pair Problem
Description
LeetCode Problem 1014.
You are given an integer array values where values[i] represents the value of the i^th sightseeing spot. Two sightseeing spots i and j have a distance j - i between them.
The score of a pair (i < j) of sightseeing spots is values[i] + values[j] + i - j: the sum of the values of the sightseeing spots, minus the distance between them.
Return the maximum score of a pair of sightseeing spots.
Example 1:
Input: values = [8,1,5,2,6]
Output: 11
Explanation: i = 0, j = 2, values[i] + values[j] + i - j = 8 + 5 + 0 - 2 = 11
Example 2:
Input: values = [1,2]
Output: 2
Constraints:
2 <= values.length <= 5 * 10^41 <= values[i] <= 1000
Solution
Approach: One Pass with the Best Left Spot
Trying every pair is O(n2). The trick is to split the score into a part that depends only on i and a part that depends only on j:
values[i] + values[j] + i - j = (values[i] + i) + (values[j] - j)
For a fixed right spot j, the best partner is simply the i < j with the largest values[i] + i. So we walk j from left to right and keep bestLeft, the largest values[i] + i seen so far:
- The best score ending at
jisbestLeft + values[j] - j; keep the maximum over allj. - Then update
bestLeftwithvalues[j] + j, so thatjcan be the left spot of a later pair.
Updating bestLeft after using it makes sure i < j: a spot is never paired with itself.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxScoreSightseeingPair(self, values: List[int]) -> int:
best = 0
best_left = 0 # max of values[i] + i over the spots i to the left of j
for j, v in enumerate(values):
best = max(best, best_left + v - j)
best_left = max(best_left, v + j)
return best