[LeetCode] 1014. Best Sightseeing Pair explained
Problem
Approach
Note that the score
value consists of two parts.
We are going to find the index of best left pair as we iterate through the values, and cache them in maxLeftScore
.
i
: index of left pair candidate.j
: index of right pair candidate.
At each time we move j
,
- Can index
j-1
can be the newi
? Then updatemaxLeftScore
. - Update
maxScore
value withmax(maxScore, score(i,j))
.
Code
typedef vector<int> vi;
class Solution {
public:
static inline int maxScoreSightseeingPair(vi &values) {
int n= values.size(), maxLeftScore= 0, maxScore= 0;
for (int j=1; j < n; ++j) {
maxLeftScore= max(maxLeftScore, values[j-1]+j-1);
maxScore= max(maxScore, values[j]-j+maxLeftScore);
}
return maxScore;
}
};
Complexity
- Time: \(O(N)\)
- Space: \(O(1)\)
Leave a comment