1014. Best Sightseeing Pair
1014. Best Sightseeing Pair
[Problem]
Intuition
- View the problem as maximizing
values[i] + i
+values[j] - j
Approach
- Separate the components:
1 2
=> maxi = values[i] + i => maxScore = maxi + values[j] - j
maxi
stores maximum value forvalues[i] + i
maxScore
is the max score possible.- Initialize
maxi
andmaxScore
to 0 initially. - The for loop:
- For
i=0
, the first spot is theith
spot, we cannot calculatemaxScore
yet without second spot. - From
i=1
toi=n-1
:- Keep updating
maxScore
1 2 3 4 5 6
if(i > 0){ int j = i; // keep updating maximum score maxScore = Math.max(maxScore, maxi + values[j] - j); }
- Keep updating
maxi
1
maxi = Math.max(maxi, values[i] + i);
- Keep updating
- For
Complexity Analysis
- Time Complexity: O(n)
- Single pass through the array.
- Space Complexity: O(1)
- No additional space used.
Reference Image
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public int maxScoreSightseeingPair(int[] values) {
return findMaxScore(values);
}
public int findMaxScore(int[] values){
int n = values.length;
int maxi = 0;
int maxScore = 0;
for(int i = 0; i < n; i++){
// check for 2nd spot(jth spot)
if(i > 0){
int j = i; // using variable `j` for better understanding
// keep updating maximum score
maxScore = Math.max(maxScore, maxi + values[j] - j);
}
// update the ith spot when a higher value is found
maxi = Math.max(maxi, values[i] + i);
}
return maxScore;
}
}
This post is licensed under CC BY 4.0 by the author.