LeetCode 1014 Best Sightseeing Pair DP
You are given an integer array values
where values[i]
represents the value of the i
th 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.
Solution
设 \(dp[j]\) 表示以 \(j\) 结尾的答案,转移方程:
\[dp[j] = \max_i(v[i]+v[j]+i-j)=v[j]-j+\max_i(v[i]+i)
\]
因此只需要维护每个位置结尾的 \(\max_i(v[i]+i)\)
点击查看代码
class Solution {
private:
int dp[50004];
int MAX = -1;
int add[50004];
public:
int maxScoreSightseeingPair(vector<int>& values) {
int n = values.size();
if(n==2){return values[0]+values[1]-1;}
for(int i=0;i<n;i++){
if(i==0)add[i] = values[i]+i;
else{
add[i] = max(add[i-1],values[i]+i);
}
}
// dp[j] = max_i(values[i]+values[j]+i-j)
// = values[j]-j+max_i(values[i]+i)
for(int j=1;j<n;j++){
dp[j] = values[j]-j+add[j-1];
MAX = max(MAX, dp[j]);
}
return MAX;
}
};