Thinking process - TLE - DP

O (n ^ 2)

public class Solution {
    public boolean canJump(int[] nums) {
        if (nums.length <= 1) return true;

        boolean[] dp = new boolean[nums.length];
        dp[0] = true;

        for (int i = 0; i < nums.length - 1; ++i) {
            if (!dp[i]) break;

            int k = 1;
            while (i + k < nums.length && k <= nums[i]) {
                dp[i + k] = true;
                k++;
            }
        }

        return dp[nums.length - 1];
    }
}

Thinking process - Greedy

a variable to remember how far it can get

O (n)

mistakes

don't forget to check whether it can get the index so far

public class Solution {
    public boolean canJump(int[] nums) {
        if (nums.length <= 1) return true;

        int maxIndex = 0;

        for (int i = 0; i < nums.length - 1; ++i) {
            if (maxIndex < i) break;
            if (i + nums[i] < Integer.MAX_VALUE) {
                maxIndex = Math.max(i + nums[i], maxIndex);
            }
        }

        return maxIndex >= nums.length - 1;
    }
}

results matching ""

    No results matching ""