classSolution {publicbooleancanJump(int[] nums) {// use greedy // max reach position index = max steps + current position = nums[i] + i// so in next round, if current position index > max reach position index, it cant reach this positionint max =0;for (int i =0; i <nums.length; i++) {if (i > max) returnfalse; max =Math.max(max, nums[i] + i); }returntrue; }}
0 1 2 3 4 => i > max => 4 > max
[3,2,1,0,4]
3 3 3 3
faster than 100%
classSolution {publicbooleancanJump(int[] nums) {int max =0;for (int i =0; i <nums.length; i++) {if (i > max) returnfalse;if (max >=nums.length-1) returntrue; // 達到終點提早返回結果 max =Math.max(max, i + nums[i]); }returntrue; }}