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.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
2 <= values.length <= 5 * 104
1 <= values[i] <= 1000
Similar Problem
Solution
Method 1 - Using Kadane’s Algorithm
The problem requires us to find the maximum score of a pair of sightseeing spots, where the score is given by values[i] + values[j] + i - j
with the condition i < j
.
To simplify the problem, notice that the expression can be rearranged:
$$
\text{score} = values[i] + i + values[j] - j
$$
From this rearrangement, “values[i] + i
” can be seen as one component and “values[j] - j
” as another. Our goal becomes finding the maximum of “values[i] +
i” up to i < j
and then the maximum values[j] - j
for j > i
.
We can use a single scan with dynamic programming:
- Initialize
maxI
tovalues[0] + 0
. - Iterate over the array and compute
maxI
and the current score. - Update the maximum score if the current score is greater than the previously recorded maximum score.
- Update
maxI
to be the maximum value of its previous value andvalues[i] + i
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
because we traverse the array only once. - 🧺 Space complexity:
O(1)
since we use a constant amount of extra space.