Second element is 3, so can make at most 3 jumps: eg to 5 or 2 or 9.
Another example:
Input: 1, 0
Ouput: -1
Explanation: the first element is 1, so can only go to 0. Then can not make any jumps, so we can not reach the end of the array.
#include <iostream> using namespace std; int walk(int *arr, int len); int walk(int *arr, int len) { if (len <=0) { return 0; } if(*arr <= 0) { return -1; } //print the element indicating the max steps we can take cout<<*arr<<" "; //we can reach the end of array by this element if(len == 1 || *arr > len-1) { return 1; } int max_step = *arr; //this array has at least two elements //we suppose the nearest element can proceed further int *pos = arr+1; int *p; for (p = arr+2; p<=arr+max_step; p++) { //if the next element can proceed further, then mark the position. if (*p > *pos-(p-pos)) { pos = p; } } int steps = walk(pos, len-(pos-arr)); if (steps == -1) { return -1;//we can never reach the end } else { return 1+steps;//increment the steps } } int main() { int arr[] = {1,3,5,2,4,3,1,2,0,0}; int steps = walk(arr, sizeof(arr)/sizeof(int)); cout<<endl<<"the steps:"<<steps<<endl; return 0; }