-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy path1696-jump-game-vi.py
36 lines (30 loc) · 1.06 KB
/
1696-jump-game-vi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def maxResult(self, nums: List[int], k: int) -> int:
dp = [float('-inf') for _ in range(len(nums))]
dp[0] = nums[0]
for right in range(1, len(nums)):
for left in range(max(0, right - k), right):
dp[right] = max(dp[right], dp[left] + nums[right])
return dp[- 1]
# time O(nk)
# space O(n)
# using dp (this will TLE)
from collections import deque
class Solution:
def maxResult(self, nums: List[int], k: int) -> int:
dp = [float('-inf') for _ in range(len(nums))]
dp[0] = nums[0]
queue = deque([])
for right in range(len(nums)):
left = right - k
while queue and queue[0] < left:
queue.popleft()
if queue:
dp[right] = dp[queue[0]] + nums[right]
while queue and dp[queue[- 1]] <= dp[right]:
queue.pop()
queue.append(right)
return dp[- 1]
# time O(n)
# space O(n)
# using stack and queue and montonic and monotonic queue and sliding window and dp