fork download
  1. #include <stdio.h>
  2. int max(int x, int y) { return (x > y)? x: y; }
  3. int minJumps(int arr[], int n)
  4. { if (n <= 1)
  5. return 0;
  6. if (arr[0] == 0)
  7. return -1;
  8. int maxReach = arr[0], step = arr[0], jump =1, i=1;
  9. for (i = 1; i < n; i++)
  10. { if (i == n-1)
  11. return jump;
  12. maxReach = max(maxReach, i+arr[i]); step--;
  13. if (step == 0)
  14. { jump++;
  15. if(i >= maxReach)
  16. return -1;
  17. step = maxReach - i;
  18. }
  19. }
  20. return -1;
  21. }
  22. int main()
  23. { int arr[]={1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
  24. int size = sizeof(arr)/sizeof(int);
  25. printf("Minimum number of jumps to reach end is %d ", minJumps(arr,size));
  26. return 0; }
  27.  
  28.  
Success #stdin #stdout 0s 4468KB
stdin
Standard input is empty
stdout
Minimum number of jumps to reach end is 3