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.
Determine if you are able to reach the last index.
For example:
A =[2,3,1,1,4], returntrue.
A =[3,2,1,0,4], returnfalse.
class Solution {
public:
bool canJump(int A[], int n)
{
if(n == 0)
return true;
int step = A[0];
int cur = 0;
while(step > 0)
{
int maxStep = step;
int id = cur;
for(int i=cur+1; i < n && i<=cur+step; i++)
{
if(maxStep < A[i])
{
maxStep = A[i];
id = i;
}
}
cur = id + maxStep;
if(cur >= n-1)
return true;
step = A[cur];
}
return cur >= n-1;
}
};