
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Score in Jump Game using 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 < 1, then
- 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 < scores[idx-1] and idx > 0, then
- currMax := scores[idx-1]
- max_pt := idx-1
- if currMax < scores[idx-1] and idx > 0, then
- 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]
- if scores[p] >= currMax, then
- if idx - k > 0, then
- scores[idx] := currMax + nums[idx]
- if max_pt >= idx - k, then
- 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 < 1: return 0 if n == 1: return nums[-1] for idx in range(1,n): if max_pt >= idx - k: if currMax < scores[idx-1] and idx > 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
Advertisements