-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathJumpGame.java
46 lines (38 loc) · 1.2 KB
/
JumpGame.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package java1.algorithms.dynamicProgramming;
public class JumpGame {
//Greedy:- TC:O(n) SC:O(1)
private static boolean canJump1(int[] nums) {
int goalPost = nums.length-1;
for(int i= nums.length-1; i>=0; i--) {
int jumpDistance = i + nums[i];
if(jumpDistance >= goalPost) {
goalPost = i;
}
}
return goalPost == 0;
}
//DP:- TC:O(n*2) SC:O(n)
private static boolean canJump2(int[] nums) {
if(nums.length == 1) return true;
if(nums[0] == 0) return false;
boolean[] dp = new boolean[nums.length];
dp[0] = true;
for(int i=1; i<nums.length; i++){
for(int j=0; j<i; j++) {
if(dp[j] && j+ nums[j] >=i) {
dp[i] = true;
break;
}
}
}
return dp[nums.length-1];
}
public static void main(String[] args) {
int[] nums1 = {2,3,1,1,4};
int[] nums2 = {3,2,1,0,4};
System.out.println(canJump1(nums1));
System.out.println(canJump1(nums2));
System.out.println(canJump2(nums1));
System.out.println(canJump2(nums2));
}
}