Program to find maximum score we can get in jump game in Python

Suppose we have an array called nums and another value k. We are at index 0. In one move, we can jump at most k steps right without going outside the boundaries of the array. We want to reach the final index of the array. For jumping we get score, that is the sum of all nums[j] for each index j we visited in the array. We have to find the maximum score we can get.

So, if the input is like nums = [1,-2,-5,7,-6,4] k = 2, then the output will be 10 because, we jump in this sequence [1, -2, 7, 4], then we will get maximum point, and that is 10.

To solve this, we will follow these steps −

  • n := size of nums
  • scores := an array of size n and filled with 0
  • scores[0] := nums[0]
  • currMax := scores[0]
  • max_pt := 0
  • if n
  • return 0
  • if n is same as 1, then
    • return last element of nums
  • for idx in range 1 to n - 1, do
    • if max_pt >= idx - k, then
      • if currMax 0, then
        • currMax := scores[idx-1]
        • max_pt := idx-1
    • otherwise,
      • if idx - k > 0, then
        • currMax := scores[idx-k]
        • max_pt := idx - k
        • for p in range idx-k to idx, do
          • if scores[p] >= currMax, then
            • max_pt := p
            • currMax := scores[p]
    • scores[idx] := currMax + nums[idx]
  • last element of scores := currMax + nums[-1]
  • return last element of scores
  • Example

    Let us see the following implementation to get better understanding −

    def solve(nums, k):
       n = len(nums)
       scores = [0] * n
       scores[0] = nums[0]
       currMax = scores[0]
       max_pt = 0
    
       if n = idx - k:
             if currMax  0:
                currMax = scores[idx-1]
                max_pt = idx-1
          else:
             if idx - k > 0:
                currMax = scores[idx-k]
                max_pt = idx - k
                for p in range(idx-k, idx):
                   if scores[p] >= currMax:
                      max_pt = p
                      currMax = scores[p]
          scores[idx] = currMax + nums[idx]
       scores[-1] = currMax + nums[-1]
       return scores[-1]
    
    nums = [1,-2,-5,7,-6,4]
    k = 2
    print(solve(nums, k))

    Input

    [1,-2,-5,7,-6,4], 2
    

    Output

    10
    Updated on: 2021-10-06T11:21:46+05:30

    765 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements