You are given a 0-indexed array nums of n integers and an integer target.
You are initially positioned at index 0. In one step, you can jump from index i to any index j such that:
0 <= i < j < n
-target <= nums[j] - nums[i] <= target
Return the maximum number of jumps you can make to reach index n - 1.If there is no way to reach index n - 1, return -1.
이 문제는 DP(동적계획법)으로 풀어야 하는 문제이다.
class Solution {
public int maximumJumps(int[] nums, int target) {
int[] dp = new int[nums.length];
Arrays.fill(dp, -1);
dp[0] = 0;
for (int i = 0; i < nums.length; i++) {
if (dp[i] == -1) continue;
for (int j = i + 1; j < nums.length; j++) {
if (Math.abs(nums[i] - nums[j]) <= target)
dp[j] = Math.max(dp[j], dp[i] + 1);
}
}
return dp[nums.length-1];
}
}
dp[]
를 nums 배열의 길이만큼 선언한다. dp 배열의 길이가 최대일 경우가 nums.length
만큼 일테니까dp[]
를 -1로 채운 후, 시작위치인 dp[0] = 0
으로 초기화dp[i] == -1
이라면 도달 불가능한 위치라는 뜻int j = i + 1
인 이유: j는 i보다 항상 뒷 번호이어야 하니까dp[i] + 1인 이유
: 이전까지 누적된 점프 수 + 이번 점프 1번