`class Solution {
public:
bool canJump(int A[], int n) {
int nearest=n-1;
for(int i=n-2;i>=0;--i)
{
if(i+A[i]>=nearest)
nearest=i;
}
return nearest==0;
}
};`
Nice code, but you don't handle the case n = 0. Here is my code, every time we just need to check the reachable states. If the current state is not reachable, return false, and if the current state is beyond the last state, return true.
Last statement 'n == 0' is for handling the case n = 0.
bool canJump(int A[], int n) {
for (int p = 0, i = 0; i < n && i <= p; i++) {
p = max(i+A[i], p);
if (p >= n-1) return true;
}
return n == 0;
}