#1014

Best Sightseeing Pair

Medium
ArrayDynamic ProgrammingArrayDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of checking all pairs, we can keep track of the best score we can achieve for the first sightseeing spot as we iterate through the list. This allows us to calculate the maximum score in a single pass.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to keep track of the maximum score and another to keep track of the best value of the first sightseeing spot adjusted for its index.
  2. 2Step 2: Iterate through the array, updating the best value as we go.
  3. 3Step 3: For each index j, calculate the score using the best value from previous indices and update the maximum score.
solution.py7 lines
1def maxScoreSightseeingPair(values):
2    max_score = 0
3    best_value = values[0]
4    for j in range(1, len(values)):
5        max_score = max(max_score, best_value + values[j] - j)
6        best_value = max(best_value, values[j] + j)
7    return max_score

Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) since we are using a constant amount of extra space.

  • 1The score formula can be rearranged to maximize the sum of values and minimize the distance.
  • 2Keeping track of the best previous value allows for a single pass solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.