Summary
Lets assume:
Array- arr
Integer- N
Function- minJumps()
Solution
// Function to return minimum number of jumps to end of array class Solution{ public: int minJumps(int arr[], int n){
if(arr[0] == 0 && n>1) return -1; if(n == 1) return 0;
int steps = arr[0]; int maxReach = arr[0]; int jumps = 1;
for(int i = 1; i<n; i++){
if(i == n-1) return jumps;
// Ab apan agle point par aagye to maxReach nikalo aur store kralo if(steps) { maxReach = max(maxReach, arr[i]+i);
// Ab apan agle point pr aagye hai to ek step kam kardo steps--; }
// check kro ki steps khatm to nhi ho gye if(steps == 0){
// agar end point tak pahuchne se pahale koi zero mil gya aur usse pahale koi maxReach nhi tha if(i>=maxReach) return -1;
// steps khatm hue matlab new point par aagye // yha se bhi jump lga do // apan jump tabhi lagayenge jab steps khatm ho jayenge jumps++;
// steps ko update krlo steps = maxReach - i; } }
return -1; } }; |
Answered by:> >_uncle_sam_055_
Credit:> >GeekforGeeks
Suggested blogs:
>How to configure python in jmeter?
>How to mock a constant value in Python?
>Creating a pivot table by 6 month interval rather than year
>How to Install mariaDB client efficiently inside docker?
>Can I call an API to find out the random seed in Python `hash()` function?
>How remove residual lines after merge two regions using Geopandas in python?