Algorithms and Data Structures/Coding Practices

LeetCode 45. Jump Game II

brightlightkim 2022. 7. 8. 14:33

Given an array of non-negative integers nums, 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.

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

 

Example 1:

Input: nums = [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.

Example 2:

Input: nums = [2,3,0,1,4]
Output: 2
class Solution {
    
    
    public int jump(int[] nums) {
        
        if (nums.length == 1){
            return 0;
        }
        
        if (nums.length == 2){
            return 1;
        }
        
        return calculation(0, 0, nums);
    }
    
    public int calculation(int start, int steps, int[] nums){
        int max = 0;
        int maxpos = start;
        
        if (start + nums[start] + 1 >= nums.length){
            return ++steps;
        }
        
        for (int i = 0; i < nums[start]; i++){
            int curPos = start + i + 1;
            if (curPos < nums.length){
                int comp = nums[curPos] + i + start;
                if (comp >= max){
                    max = comp;
                    maxpos = curPos;
                }
            } else {
                return ++steps;
            }
        }
        
        steps++;
        
        return calculation(maxpos, steps, nums);
    }
}