Wednesday, August 27, 2014

Jump Game

This is a typically DP problem, but using DP method to solve it is not the best way. Firstly, I will post my code for this question. Here, I think if I start from 1st index, and jump the maximum length to next, and recursively, then if end is met, return true, but not, get back to last jump, then jump the (maximum - 1) length again and try. But for this method, it is possible for each element in the range of 1st index, and it might take up to O(n^2) time. Thus it get TLE.

Solution by me:
 public class Solution {  
   public boolean canJump(int[] A) {  
     if(A.length == 0) return false;  
     int[] B = new int[A.length];  
     Arrays.fill(B,-1);  
     return canJump(A,0,B);  
   }  
   public boolean canJump(int[] A, int crntIdx, int[] B){  
     if(crntIdx >= A.length - 1){   
       B[A.length - 1] = 1;   
       return true;  
     }  
     if(B[crntIdx] != -1){   
       return (B[crntIdx] == 0 ? false:true);  
     }  
     if(A[crntIdx] == 0) {  
       B[crntIdx] = 0;  
       return false;  
     }  
     int i = A[crntIdx];  
     while(i > 0 && !canJump(A,crntIdx+i,B)){  
       i--;  
     }  
     if((crntIdx+i) < (A.length - 1)) B[crntIdx+i] = (i == 0 ? 0: 1);  
     // else B[A.length - 1] = (i == 0 ? false: true);  
     else return true;  
     return (B[crntIdx+i] == 0 ? false:true);  
   }   
 }  


Solution by Code Ganker .In his post, he considers the "local maximum and global maximum reach" the elements in array A could get to, and if the global reach is larger than last index, then it must be TRUE.
Thanks to Code Ganker for his brilliant idea.
 public boolean canJump(int[] A) {  
   if(A==null || A.length==0)  
     return false;  
   int reach = 0;  
   for(int i=0;i<=reach&&i<A.length;i++)  
   {  
     reach = Math.max(A[i]+i,reach);  
   }  
   if(reach<A.length-1)  
     return false;  
   return true;  
 }  

No comments:

Post a Comment