File tree 1 file changed +37
-0
lines changed
1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
1
+ package medium ;
2
+
3
+ public class JumpGame {
4
+
5
+ public static boolean canJump_greedy (int [] nums ) {
6
+ int farthest = nums [0 ];
7
+ for (int i = 0 ; i < nums .length ; i ++){
8
+ if (i <= farthest && nums [i ]+i > farthest ) {
9
+ //i <= farthest is to make sure that this current i is within the current range
10
+ // nums[i]+i > farthest is to make sure that it's necessary to update farthest with current nums[i]+i
11
+ farthest = nums [i ]+i ;
12
+ }
13
+ }
14
+ return farthest >= nums .length -1 ;
15
+ }
16
+
17
+ //this normal dp ends in TLE for extreme test cases
18
+ public static boolean canJump_dp (int [] nums ) {
19
+ boolean [] can = new boolean [nums .length ];
20
+ can [0 ] = true ;
21
+ for (int i = 0 ; i < nums .length ; i ++){
22
+ int reach = nums [i ];
23
+ if (can [i ]){
24
+ for (int j = i +1 ; j < nums .length && j <= i +reach ; j ++){
25
+ can [j ] = true ;
26
+ }
27
+ }
28
+ }
29
+ return can [nums .length -1 ];
30
+ }
31
+
32
+ public static void main (String ...strings ){
33
+ // int[] nums = new int[]{1,2};
34
+ int [] nums = new int []{0 ,2 ,3 };
35
+ System .out .println (canJump_greedy (nums ));
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments