You are initially standing at index 0. In one move, you can jump at most k steps forward without going outside the boundaries of the array. That is, you can jump from index i to any index in the range [i + 1, min(n - 1, i + k)] inclusive.
You want to reach the last index of the array (index n - 1). Your score is the sum of all nums[j] for each index j you visited in the array.
Return the maximum score you can get.
Example 1:
Input: nums = [1,-1,-2,4,-7,3], k = 2
Output: 7
Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
Example 2:
Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
Example 3:
Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
Output: 0
Constraints:
1 <= nums.length, k <= 105
-104 <= nums[i] <= 104
解法1:DP。会超时
class Solution {
public:
int maxResult(vector<int>& nums, int k) {
int n = nums.size();
vector<int> dp(n + 1, INT_MIN);
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
if (i >= j) {
dp[i] = max(dp[i], dp[i - j] + nums[i - 1]);
}
}
}
return dp[n];
}
};
解法2:DP+单调队列。
注意:
class Solution {
public:
int maxResult(vector<int>& nums, int k) {
int n = nums.size();
int res = INT_MIN;
vector<int> dp(n, INT_MIN);
dp[0] = nums[0];
deque<int> dq;
dq.push_back(0);
for (int i = 1; i < n; i++) {
while (i - dq.front() > k) dq.pop_front();
dp[i] = nums[i] + dp[dq.front()]; //不要用dp[i]=max(dp[i], nums[i] + dp[dq.front()])
while (!dq.empty() && dp[dq.back()] < dp[i]) {
dq.pop_back();
}
dq.push_back(i);
}
return dp[n - 1];
}
};