Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2
. (Jump 1
step from index 0 to 1, then 3
steps to the last index.)
Analysis
Using greedy idea, every time get the max length. Details see the code. Matain a maximum scope
java
public int jump(int[] A) {
int n = A.length;
if(n==0 ||n==1) return 0;
int max=0;
int start = 0;
int njump = 0;
while(start<n){
max = Math.max(max, A[start]+start);
if(max>0)
njump++;
if(max>=n-1)
return njump;
int temp=0;
for(int j = start+1;j<=max;j++){
if(A[j]+j>temp){
temp = A[j]+j;
start = j;
}
}
}
return njump;
}
c++
int jump(int A[], int n) {
int start = 0;
int end = 0;
int count = 0;
if(n==1) return 0;
while(end<n){
int max = 0;
count++;
for(int i = start; i<=end;i++){
if(A[i]+i >= n-1){
return count;
}
if(A[i]+i > max){
max = A[i]+i;
}
}
start = end+1;
end = max;
}
}