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.
思路
表达式可以分成两部分,values[i] + i 和 values[j] - j,
使用dp动态规划将求values[i] + i的最大值,然后对j进行遍历。
时间复杂度为O(n),空间复杂度O(n)。
(可以用变量表示values[i] + i 的最大值,将空间复杂度降低为O(1)。
状态转移方程
dp[i] = max(dp[i-1], values[i] + i)
边界条件
dp[0] = values[0]
说明
LeetCode有运行时间排名,我为了加快程序的运行速度,将max函数改写成了if-else结果,用时减少了25%。
一般而言,自己手写函数或者结构比调用库函数快。
代码
class Solution {
public:
int maxScoreSightseeingPair(vector<int>& values) {
int len = values.size();
int dp[50005] = {0};
dp[0] = values[0];
int maxn = values[0] + values[1] - 1;
for(int i = 1; i < len; i++)
{
if(dp[i-1] > values[i] + i)
dp[i] = dp[i-1];
else
dp[i] = values[i] + i;
if(values[i] - i + dp[i-1] > maxn)
maxn = values[i] - i + dp[i-1];
}
return maxn;
}
};