codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[LeetCode] 45. Jump Game II #32

Open cs-cordero opened 5 years ago

cs-cordero commented 5 years ago

🎵 Jumpman. Jumpman. Jumpman. Them boys up to something 🎵

Link: https://leetcode.com/problems/jump-game-ii/

Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Your goal is to reach the last index in the minimum number of jumps.

Example: Input: [2,3,1,1,4] Output: 2

Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Note: You can assume that you can always reach the last index.

cs-cordero commented 5 years ago

Based on what Leetcode says about my runtime and memory usage, there's probably a better way to do this.

Runtime: 76 ms, faster than 32.60% of Python3 online submissions for Jump Game II. Memory Usage: 15.2 MB, less than 5.00% of Python3 online submissions for Jump Game II.


class Solution:
def jump(self, nums: List[int]) -> int:
dp = [len(nums) for _ in range(len(nums))]
dp[0] = 0
    for jumpman in range(len(dp)):
        current_jump_count = dp[jumpman]
        possible_jump_count = nums[jumpman]
        end_jump = min(len(dp)-1, jumpman+possible_jump_count)
        for next_jump in range(end_jump, jumpman, -1):
            if dp[next_jump] <= current_jump_count+1:
                break

            dp[next_jump] = current_jump_count + 1
    return dp[-1]