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]
, return true
. A =
[3,2,1,0,4]
, return false
.
class Solution {
public:
bool canJump(int A[], int n) {
int current = 0;
int reach = A[0];
while(current <= reach) {
if (reach >= n-1) return true;
reach = max(reach, current+A[current]);
current++;
}
return false;
}
};
No comments:
Post a Comment