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: Find Maximum Score81526i=0i=1i=2i=3i=4distance = 2-0 = 2Score Formula: values[i] + values[j] + i - jPair (0,2): 8 + 5 + 0 - 2 = 11Maximum Score: 11Higher values compensate for distance penalty
Understanding the Visualization
1
Input Array
Array of sightseeing spot values [8,1,5,2,6]
2
Score Formula
score = values[i] + values[j] + i - j (distance penalty)
3
Find Maximum
Return the highest score among all pairs
Key Takeaway
🎯 Key Insight: Rewrite the formula to separate first and second spot contributions for optimal solution
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