Best Sightseeing Pair - Problem

You are given an integer array values where values[i] represents the value of the ith 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.

Input & Output

Example 1 — Basic Case
$ Input: values = [8,1,5,2,6]
Output: 11
💡 Note: Best pair is (i=0, j=2): values[0] + values[2] + 0 - 2 = 8 + 5 + 0 - 2 = 11
Example 2 — Adjacent Elements
$ Input: values = [1,2]
Output: 2
💡 Note: Only one pair possible: values[0] + values[1] + 0 - 1 = 1 + 2 + 0 - 1 = 2
Example 3 — Large Distance Penalty
$ Input: values = [10,1,1,1,20]
Output: 26
💡 Note: Best pair is (i=0, j=4): values[0] + values[4] + 0 - 4 = 10 + 20 + 0 - 4 = 26

Constraints

  • 2 ≤ values.length ≤ 5 × 104
  • 1 ≤ values[i] ≤ 1000

Visualization

Tap to expand
Best Sightseeing Pair INPUT values array: 8 i=0 1 i=1 5 i=2 2 i=3 6 i=4 Score Formula: values[i] + values[j] + i - j Example: i=0, j=2 8 + 5 + 0 - 2 = 11 Rewrite as: (values[i] + i) + (values[j] - j) ALGORITHM STEPS 1 Initialize maxLeft = values[0] + 0 = 8 maxScore = 0 2 Iterate j from 1 to n-1 For each j, compute score = maxLeft + values[j] - j 3 Update maxScore maxScore = max(maxScore, score) 4 Update maxLeft maxLeft = max(maxLeft, values[j] + j) j val[j]-j maxLeft score 1 0 8 8 2 3 8 11 3 -1 8 7 4 2 8 10 FINAL RESULT Best Sightseeing Pair Found 8 i=0 5 j=2 distance=2 Score Calculation values[0] = 8 values[2] = 5 8 + 5 + 0 - 2 = 11 OUTPUT 11 Maximum Score: OK Key Insight: By rewriting the score as (values[i] + i) + (values[j] - j), we can track the maximum (values[i] + i) seen so far. This transforms O(n^2) brute force into O(n) one-pass solution. TutorialsPoint - Best Sightseeing Pair | One Pass Optimization
Asked in
Facebook 25 Amazon 20 Google 15
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen