45. Jump Game II

class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ curr = 0 # index of current position prev_furthest = 0 # previous furthest. Used as the start point+1 in the for loop. Save some iterations curr_furthest = curr + nums[curr] # index of current furthest position. Used as the end point of the for loop step = 0 while(curr_furthest < len(nums)-1): max_distance = 0 # placeholder: how far can we jump? next_pos = -1 # placeholder: where to jump next? # this loop compares all possible jump positions and select the one with biggest coverage for pos in range(prev_furthest+1, curr_furthest+1, 1): # why starts from prev_furthest instead of curr? Because if there is overlap, then the elements # greater than curr and smaller than prev_furthest must not have been chosen, or it will be chosen # in the last round already. Draw a picture if nums[pos] + pos - curr > max_distance: next_pos = pos max_distance = nums[pos] + pos - curr # the loop ends early when max_distance is zero and we have not reached the end if (max_distance == 0 and curr_furthest < len(nums)-1): return -1 # after the loop, we really make the jump by updating variables step += 1 curr = next_pos prev_furthest = curr_furthest curr_furthest = curr + nums[curr] if (curr == len(nums)-1): # no last jump return step else: # the last jump return step + 1
Mistakes:
1. Do not understand this algorithm. Interval covering. The key insight is for next step, we take the position that will have the biggest coverage. Why? Because we are still going to examine its coverage one by one in the next step. So at this step, other positions coverage will be included in this position's coverage. See the competitive programming book by Steven and Felix page 91. Classic interval covering problem.
2. An optimization is in the for loop, check from previous furthest to current furthest. Why not from curr to curr furthest? Because the nodes between curr and prev_furthest has already be examined last time, and they are not chosen. Their range is completely covered in the range of this node.
3. In updating max_distance, made mistake about how to calculate max_distance.

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.