Simple Java O(n) solution with explanation


  • 3
    The main idea is to see if current element can be reached by previous max jump. 
    If not, return false. If true, renew the max jump. (maxjump = i+nums[i]>maxjump?i+nums[i]:maxjump;)
    public class Solution {
    public boolean canJump(int[] nums) {
        if(nums.length==0){
            return false;
        }
        int maxjump = nums[0];
        for(int i = 0;i<nums.length;i++){
            if(i>maxjump){
                return false;
            }
            if(i+nums[i]>maxjump){
                maxjump = i+nums[i];
            }
        }
        return true;
    }
    }

Log in to reply
 

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