O(n) 9ms solution with explaination


  • 0
    S

    The idea is very simple, each time we find the farthest boundary we can reach in each step.
    For example, [2,3,1,1,4], at the beginning we at index 0, the farthest index we can reach is 2. Next step, we can go through index 1 and 2, and we can see that the farthest next step is 1 + 3 = 4. And this goes on till we reach the end.

    public class Solution {
        public int jump(int[] nums) {
            int index = 1;
            int boundary = nums[0];
            int count = 0;
            int nextBoundary = 0;
            while(index < nums.length){
                while(index < nums.length && index <= boundary){
                    nextBoundary = Math.max(nextBoundary, index + nums[index]);
                    index++;
                }
                count++;
                boundary = nextBoundary;
            }
            return count;
        }
    }
    

Log in to reply
 

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