13 lines Greedy solution


  • 0
    A

    assuming you walk from the last element to the first element of array. You only need to keep the track of the farthest element you can reach in 1 jump. And keep the idx of the element that you can reach in 1 jump. Then keep doing this process till idx == 0;

    public class Solution {
        public int Jump(int[] nums) {
            if (null == nums || nums.Length == 0) return 0;
            var last = nums.Length - 1;
            var counter = 0;
            while (last != 0)
            {   // keep track the lowest idex of last reachable
                var temp = last;
                for (var i = last - 1; i >= 0; i--)
                    if (last - i <= nums[i] && temp > i)
                        temp = i;
                last = temp;
                counter++;
            }
            return counter;
        }
    }```

Log in to reply
 

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