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]
, return true
.
A = [3,2,1,0,4]
, return false
.
Subscribe to see which companies asked this question
class Solution {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
int ans = 0;
if(len == 0) return true;
ans = nums[0];
//dp[i+1] = max(dp[i]-1, nums[i-1]-1) dp[0] = nums[0]
for(int i=1; i < len; i++) {
ans = max(ans-1, nums[i-1]-1);
if (ans < 0) return false;
// cout << ans << endl;
}
if(ans >= 0) return true;
else return false;
}
};