PROBLEM 47: Minimum Number of Jumps
A Program to find the minimum number of jumps to reach the end of the array (starting from the first element). (Interview Question)
Author - Ajay Zad
Date - 17/03/2022
import sys
n = int(input("Enter the value for n :"))
l = []
for i in range(0,n):
m = int(input("Enter the elements in the array :"))
l.append(m)
i = 0
j = l[0]
cnt = 0
cnt1 = 0
while i < n :
while j > 0:
j = j - 1
cnt = cnt + 1
else:
try:
j = l[cnt]
#cnt1 will keep track of no. of jumps
cnt1 = cnt1 + 1
except:
print("Number of jumps required = ",cnt1)
sys.exit()
i = cnt
print("Number of jumps required = ",cnt1)
The above code is in Python Language.
Input :
Enter the value for n : 5
Enter the elements in the array : 1
Enter the elements in the array : 2
Enter the elements in the array : 2
Enter the elements in the array : 3
Enter the elements in the array : 4
Output :
Number of jumps required = 3
No comments:
Post a Comment