Problem Description
You are given a 0-indexed integer array nums and a cost array costs. Starting at index 0, you can jump from index i to j (with i < j) if one of the following conditions holds:
- nums[i] <= nums[j] and every element between i and j is strictly less than nums[i], or
- nums[i] > nums[j] and every element between i and j is greater than or equal to nums[i].
The cost of jumping to index j is given by costs[j]. Your task is to compute the minimum total cost required to reach index n - 1.
Key Insights
- The problem can be seen as finding the shortest path in a directed acyclic graph (DAG) where nodes are indices.
- A dynamic programming (DP) solution is applicable where dp[i] represents the minimum cost to reach index i.
- Two monotonic stacks are used to efficiently process valid jumps based on the two conditions (increasing and decreasing jumps).
- The increasing stack handles jumps where nums[i] <= nums[j] by ensuring the intermediate elements are less than nums[i].
- The decreasing stack handles jumps where nums[i] > nums[j] by ensuring the intermediate elements are greater than or equal to nums[i].
Space and Time Complexity
Time Complexity: O(n), as each index is processed with amortized constant time stack operations.
Space Complexity: O(n), used by the dp array and the two stacks.
Solution
We solve the problem using a DP approach where dp[i] holds the minimum cost to reach index i. We iterate through the array while maintaining two monotonic stacks:
- For indices where nums[i] should be less than or equal to nums[j], we pop from the increasing stack until nums[stack.top()] <= nums[i]. Then, we update dp[i] using the top of this stack.
- Similarly, for the second condition, we maintain a decreasing stack by popping until nums[stack.top()] >= nums[i] and then update dp[i]. Finally, the answer is given by dp[n - 1].