Jump Game VIII Problem
Description
LeetCode Problem 2297.
You are given a 0-indexed integer array nums of length n. You are initially standing at index 0. You can jump from index i to index j where i < j if:
nums[i] <= nums[j]andnums[k] < nums[i]for all indexeskin the rangei < k < j, ornums[i] > nums[j]andnums[k] >= nums[i]for all indexeskin the rangei < k < j.
You are also given an integer array costs of length n where costs[i] denotes the cost of jumping to index i.
Return the minimum cost to jump to the index n - 1.
Example 1:
Input: nums = [3,2,4,4,1], costs = [3,7,6,4,2]
Output: 8
Explanation: You start at index 0.
- Jump to index 2 with a cost of costs[2] = 6.
- Jump to index 4 with a cost of costs[4] = 2.
The total cost is 8. It can be proven that 8 is the minimum cost needed.
Two other possible paths are from index 0 -> 1 -> 4 and index 0 -> 2 -> 3 -> 4.
These have a total cost of 9 and 12, respectively.
Example 2:
Input: nums = [0,1,2], costs = [1,1,1]
Output: 2
Explanation: Start at index 0.
- Jump to index 1 with a cost of costs[1] = 1.
- Jump to index 2 with a cost of costs[2] = 1.
The total cost is 2. Note that you cannot jump directly from index 0 to index 2 because nums[0] <= nums[1].
Constraints:
n == nums.length == costs.length1 <= n <= 10^50 <= nums[i], costs[i] <= 10^5
Solution
Approach: Monotonic Stack + DP
From index i you can only jump to the next index with a value at least nums[i], or the next index with a smaller value. Two monotonic stack passes from right to left find both targets for every index and build the jump graph. Since jumps only go forward, process indices in order: f[j] = min(f[j], f[i] + costs[j]) for each target j of i, with f[0] = 0. The answer is f[n - 1].
Complexity: O(n) time and space, where n is the length of nums.
from collections import defaultdict
from math import inf
class Solution:
def minCost(self, nums: List[int], costs: List[int]) -> int:
n = len(nums)
g = defaultdict(list)
stk = []
for i in range(n - 1, -1, -1):
while stk and nums[stk[-1]] < nums[i]:
stk.pop()
if stk:
g[i].append(stk[-1])
stk.append(i)
stk = []
for i in range(n - 1, -1, -1):
while stk and nums[stk[-1]] >= nums[i]:
stk.pop()
if stk:
g[i].append(stk[-1])
stk.append(i)
f = [inf] * n
f[0] = 0
for i in range(n):
for j in g[i]:
f[j] = min(f[j], f[i] + costs[j])
return f[n - 1]