Skip to content

Commit e891d08

Browse files
committed
Solution as on 09-07-2022 10:00 am
1 parent 3051f8e commit e891d08

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

1696. Jump Game VI.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// 1696.✅ Jump Game VI
2+
3+
/*
4+
You are given a 0-indexed integer array nums and an integer k.
5+
6+
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.
7+
8+
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.
9+
10+
Return the maximum score you can get.
11+
12+
13+
14+
Example 1:
15+
16+
Input: nums = [1,-1,-2,4,-7,3], k = 2
17+
Output: 7
18+
Explanation: You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
19+
Example 2:
20+
21+
Input: nums = [10,-5,-2,4,0,3], k = 3
22+
Output: 17
23+
Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
24+
Example 3:
25+
26+
Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
27+
Output: 0
28+
29+
30+
Constraints:
31+
32+
1 <= nums.length, k <= 105
33+
-104 <= nums[i] <= 104
34+
*/
35+
36+
class Solution
37+
{
38+
public:
39+
int maxResult(vector<int> &nums, int k)
40+
{
41+
deque<int> q; // O(k)
42+
int n = nums.size();
43+
vector<int> dp(n); // O(n)
44+
45+
dp[n - 1] = nums[n - 1];
46+
47+
q.push_back(n - 1);
48+
49+
for (int i = n - 2; i >= 0; --i) // O(k)
50+
{
51+
if (q.front() - i > k)
52+
q.pop_front();
53+
dp[i] = nums[i] + dp[q.front()];
54+
while (q.size() && dp[q.back()] < dp[i])
55+
q.pop_back();
56+
q.push_back(i);
57+
}
58+
return dp[0];
59+
}
60+
};

0 commit comments

Comments
 (0)