-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
58 additions
and
38 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,37 @@ | ||
""" | ||
Problem: | ||
You are given an array of integers, where each element represents the maximum number of steps that can be jumped going forward from that element. | ||
Write a function to return the minimum number of jumps you must take in order to get from the start to the end of the array. | ||
You are given an array of integers, where each element represents the maximum number of | ||
steps that can be jumped going forward from that element. Write a function to return | ||
the minimum number of jumps you must take in order to get from the start to the end of | ||
the array. | ||
Example: | ||
Input = [6, 2, 4, 0, 5, 1, 1, 4, 2, 9] | ||
Output = 2 (as the optimal solution involves jumping from 6 to 5, and then from 5 to 9) | ||
For example, given [6, 2, 4, 0, 5, 1, 1, 4, 2, 9], you should return 2, as the optimal | ||
solution involves jumping from 6 to 5, and then from 5 to 9. | ||
""" | ||
|
||
from sys import maxsize | ||
from typing import List | ||
|
||
|
||
def get_min_jumps(arr): | ||
def get_min_jumps(arr: List[int]) -> int: | ||
length = len(arr) | ||
# using dynamic programming to reduce O(n ^ n) problem to O(n ^ 2) | ||
dp = [0 for _ in range(length)] | ||
for i in range(length - 2, -1, -1): | ||
# updating the minimum hops for each position | ||
if arr[i]: | ||
dp[i] = min(dp[i + 1 : i + arr[i] + 1]) + 1 | ||
else: | ||
dp[i] = maxsize | ||
return dp[0] | ||
|
||
|
||
# DRIVER CODE | ||
print(get_min_jumps([6, 2, 4, 0, 5, 1, 1, 4, 2, 9])) | ||
if __name__ == "__main__": | ||
print(get_min_jumps([6, 2, 4, 0, 5, 1, 1, 4, 2, 9])) | ||
|
||
|
||
""" | ||
SPECS: | ||
TIME COMPLEXITY: O(n ^ 2) | ||
SPACE COMPLEXITY: O(n) | ||
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters