This can be solved by using Car and fuel tank analogy.


  • 0
    A

    Lets rephrase the question,
    We want to reach the end of the road(end of the array), the numbers in the Array are fuelTanks one the road.
    For tarvelling to the next fuelTank(number) we will lose a fuel unit in your current tank.

    Ans:
    At each number(fuel tank), we pick up whichever is highest our current fuelTank in the car OR the fuel tank that is in the road

    public class Solution {
        public boolean canJump(int[] fuelRoad) {
            if(fuelRoad.length<=1){
                return true;
            }
            //there is no need for the fuel at the end- this just messes with my code, so making it zero
            fuelRoad[fuelRoad.length-1]=0;
            //lets initilize the car with the firstfuel tank in the road
            int carPosition=1, fuelTank=fuelRoad[0]-1;
            while(carPosition<fuelRoad.length && 
                //there has to be fuel to travel
                fuelTank>=0){
                //this is just small optimization,checks whether we will have enough fuel to reach the end
                if(carPosition+fuelTank >= fuelRoad.length-1){
                    return true;
                }
                //check which is bigger the fuel in the road or our tank
                if(fuelRoad[carPosition]>fuelTank){
                    fuelTank=fuelRoad[carPosition];
                }
                carPosition++;
                fuelTank--;
            }
            return false;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.