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.
Each element in the array represents your maximum jump length at that position.
Determine if you are able to reach the last index.
Example:
Input: arr[]={2,3,1,1,4}
Output: true
Approach
Java
public class JumpGame {public static void main(String[] args) {int nums[] = { 2, 3, 1, 1, 4 };System.out.println(canJump(nums));}static boolean canJump(int[] nums) {int n = nums.length;// set last as n-1 positionint last = n - 1;for (int i =last; i >= 0; i--) {// if i+num[i]>=last// then update lastif (i + nums[i] >= last)last = i;}if (last == 0)return true;return false;}}
C++
#include <bits/stdc++.h>using namespace std;bool canJump(vector<int>& nums){int n=nums.size();//set last as n-1 positionint last=n-1;for(int i=n-1;i>=0;i--){//if i+num[i]>=last//then update lastif(i+nums[i]>=last)last=i;}if(last==0)return true;return false;}int main(){vector<int> nums ={2,3,1,1,4};if(canJump(nums))cout<<"true\n";elsecout<<"false\n";return 0;}
No comments:
Post a Comment