Problem Description:
Level: medium
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
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
Note
This problem have two method which is Greedy and Dynamic Programming.
The time complexity of Greedy method is O(n).
The time complexity of Dynamic Programming method is O(n^2).
Solution:
Consider DP
State: f[i] means I can jump to position i
function: f[I] = OR(f(j), j < i & j+a[j] >= i, j can jum to i) — mean if there is one j can jump to i
initialize: f[0] = true
Answer: f(n-1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
public boolean canJump(int[] A) { // corner case if(A.length == 0) return false; // initialize boolean f[] = new boolean[A.length]; for(int i = 0; i < A.length; i++) { f[i] = false; } f[0] = true; for(int i = 1; i < A.length; i++) { for(int j = 0; j < i; j++) { if(f[j] && j + A[j] >= i) { f[i] = true; break; } } } return f[A.length-1]; } |