Given an array of integers, each element represents the max number of jumps that you can move forward.
Write a piece of code to find out the minimum number of elements you need to select to reach the end of the array (starting from the first element).
All integers is equal to or greater than 0.
If an element is 0, you cannot make any jumps.
-1 should be output if it is unable to reach the end of the array.
Here is an example to illustrate the question.
Sample Input: 1,3,5,2,9,3,1,1,8
Sample Output: 3
Explanation:
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 9 ->8
First element is 1, so can only go to 3.
Write a piece of code to find out the minimum number of elements you need to select to reach the end of the array (starting from the first element).
All integers is equal to or greater than 0.
If an element is 0, you cannot make any jumps.
-1 should be output if it is unable to reach the end of the array.
Here is an example to illustrate the question.
Sample Input: 1,3,5,2,9,3,1,1,8
Sample Output: 3
Explanation:
Here the min # of selections is : 3
with the sequence : 1-> 3 -> 9 ->8
First element is 1, so can only go to 3.
Second element is 3, so can make at most 3 jumps: eg to 5 or 2 or 9.
public static int ouputSolution(int[] input)
{
//Write your code here
int int_max = 21474836;
int n = input.length;
if(minJumps(input,0,n-1)==int_max)
return -1;
else
return minJumps(input,0,n-1);
}
public static int minJumps(int[] array,int start,int end)
{
int int_max = 21474836;
if(start==end) return 0;
if(array[start]==0 ) return int_max;
int min = int_max;
for(int i=start+1;i<=end && i<=start+array[start];i++)
{
int jumps = minJumps(array,i,end);
if(jumps!=int_max && jumps+1<min)
min = jumps+1;
}
return min;
}