Advertisement
Iam_Sandeep

1696.Jump Game 6

Jul 15th, 2022
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. '''
  2. You are given a 0-indexed integer array nums and an integer k.
  3.  
  4. 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.
  5.  
  6. 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.
  7.  
  8. Return the maximum score you can get.
  9. '''
  10. #method 1 Monotoic Queue
  11. Keep queue such that elements are in decreasing order
  12. class Solution:
  13.     def maxResult(self, nums: List[int], k: int) -> int:
  14.         q=deque()
  15.         n=len(nums)
  16.         q.append(n-1)
  17.         dp=[0]*n
  18.         dp[-1]=nums[-1]
  19.        
  20.         ans=0
  21.         for i in range(n-2,-1,-1):
  22.             if q[0]-i>k:
  23.                 q.popleft()
  24.             dp[i]=dp[q[0]]+nums[i]
  25.             while q and dp[q[-1]]<dp[i]:
  26.                 q.pop()
  27.             q.append(i)
  28.         return dp[0]
  29. #method 2 Using heap               
  30. import heapq as hq
  31. class Solution:
  32.     def maxResult(self, nums: List[int], k: int) -> int:
  33.         h=[]
  34.         ans=None
  35.         n=len(nums)
  36.         for i in range(n-1,-1,-1):
  37.             while h and h[0][1]-i>k:
  38.                 hq.heappop(h)
  39.             item=(-(-(h[0][0] if h else 0)+nums[i]),i)
  40.             hq.heappush(h,item)
  41.             ans=-item[0]
  42.         return ans
  43.        
  44.    
  45.                
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement