You are given a 0-indexed integer array nums
and an integer k
.
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
Solution: DP + Monotonic Queue
dp[i] = nums[i] + max(dp[j]) i – k <= j < i
Brute force time complexity: O(n*k) => TLE
Python3 / TLE
1 2 3 4 5 6 7 |
# Author: Huahua 52/58 Passed (TLE) class Solution: def maxResult(self, nums: List[int], k: int) -> int: @lru_cache(None) def dp(i: int) -> int: return nums[0] if i == 0 else nums[i] + max(dp(j) for j in range(max(0, i - k), i)) return dp(len(nums) - 1) |
This problem can be reduced to find the maximum for a sliding window that can be solved by monotonic queue.
Time complexity: O(n)
Space complexity: O(n+k) -> O(k)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua class Solution { public: int maxResult(vector<int>& nums, int k) { const int n = nums.size(); vector<int> dp(n); deque<int> q{{0}}; dp[0] = nums[0]; for (int i = 1; i < n; ++i) { dp[i] = nums[i] + dp[q.front()]; while (!q.empty() && dp[i] >= dp[q.back()]) q.pop_back(); while (!q.empty() && i - q.front() >= k) q.pop_front(); q.push_back(i); } return dp[n - 1]; } }; |
C++/O(n) Space
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Author: Huahua class Solution { public: int maxResult(vector<int>& nums, int k) { const int n = nums.size(); deque<pair<int, int>> q{{nums[0], 0}}; for (int i = 1; i < n; ++i) { const int cur = nums[i] + q.front().first; while (!q.empty() && cur >= q.back().first) q.pop_back(); while (!q.empty() && i - q.front().second >= k) q.pop_front(); q.emplace_back(cur, i); } for (const auto& [v, i] : q) if (i == n - 1) return v; return 0; } }; |