Problem Description
Given an array of integers, where each integer represents the value of a sightseeing spot, we need to determine the maximum score for a pair of sightseeing spots. The score of a pair (i, j) with i < j is calculated as values[i] + values[j] + i - j. The task is to return the maximum score obtainable.
Key Insights
- The score can be reformulated as (values[i] + i) + (values[j] - j), decoupling the contributions from the two indices.
- While iterating through the array, maintain the maximum value of (values[i] + i) seen so far.
- For every new spot j, combine the previously stored maximum with (values[j] - j) to update the answer.
- This one-pass strategy ensures an O(n) time complexity.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
The solution involves a single pass through the array, maintaining a variable (best_left) to record the maximum value of (values[i] + i) encountered so far. For each index j (starting from 1), calculate the score by adding best_left and (values[j] - j). Update the max score whenever a higher score is found, and also update the best_left for future calculations. This efficient approach leverages dynamic programming by keeping track of cumulative optimal sub-results.