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.
Example 1:
Example 2:
Solution
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public class JumpGame { public static void main(String[] args) { int [] a= {2,3,1,1,4}; System.out.println(new JumpGame().canJump(a)); } public boolean canJump(int[] nums) { int maxIndex = 0; for (int i = 0; i < nums.length; i++) { if (i > maxIndex) { return false; } maxIndex = Math.max(nums[i] + i, maxIndex); } return true; } } |
Output
We encourage you to write a comment if you have a better solution or having any doubt on the above topic.
Hi Navneet,
Solution is pretty simple and understandable.
Can you please brief about the reasoning behind it in terms of how you come up with the approach ?
Regards,
Kunal Prajapati