|
| 1 | +/// Source : https://leetcode.com/problems/jump-game-ix/ |
| 2 | +/// Author : liuyubobobo |
| 3 | +/// Time : 2022-06-09 |
| 4 | + |
| 5 | +#include <iostream> |
| 6 | +#include <vector> |
| 7 | +#include <stack> |
| 8 | + |
| 9 | +using namespace std; |
| 10 | + |
| 11 | + |
| 12 | +/// Mono Stack + DP |
| 13 | +/// Time Complexity: O(n) |
| 14 | +/// Space Complexity: O(n) |
| 15 | +class Solution { |
| 16 | +public: |
| 17 | + long long minCost(vector<int>& nums, vector<int>& costs) { |
| 18 | + |
| 19 | + int n = nums.size(); |
| 20 | + |
| 21 | + vector<int> right_larger_or_equal(n, n); |
| 22 | + vector<int> stack; |
| 23 | + for(int i = n - 1; i >= 0; i --){ |
| 24 | + while(!stack.empty() && nums[i] > nums[stack.back()]) stack.pop_back(); |
| 25 | + if(!stack.empty()) right_larger_or_equal[i] = stack.back(); |
| 26 | + stack.push_back(i); |
| 27 | + } |
| 28 | +// for(int e: right_larger_or_equal) cout << e << ' '; cout << '\n'; |
| 29 | + |
| 30 | + vector<int> right_smaller(n, n); |
| 31 | + stack.clear(); |
| 32 | + for(int i = n - 1; i >= 0; i --){ |
| 33 | + while(!stack.empty() && nums[i] <= nums[stack.back()]) stack.pop_back(); |
| 34 | + if(!stack.empty()) right_smaller[i] = stack.back(); |
| 35 | + stack.push_back(i); |
| 36 | + } |
| 37 | +// for(int e: right_smaller) cout << e << ' '; cout << '\n'; |
| 38 | + |
| 39 | + vector<long long> dp(n, LONG_LONG_MAX / 2); |
| 40 | + dp[0] = 0; |
| 41 | + for(int i = 0; i < n; i ++){ |
| 42 | + int to = right_larger_or_equal[i]; |
| 43 | + if(to < n) |
| 44 | + dp[to] = min(dp[to], dp[i] + costs[to]); |
| 45 | + |
| 46 | + to = right_smaller[i]; |
| 47 | + if(to < n) |
| 48 | + dp[to] = min(dp[to], dp[i] + costs[to]); |
| 49 | + } |
| 50 | + return dp.back(); |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | + |
| 55 | +int main() { |
| 56 | + |
| 57 | + vector<int> nums1 = {3, 2, 4, 4, 1}, costs1 = {3, 7, 6, 4, 2}; |
| 58 | + cout << Solution().minCost(nums1, costs1) << '\n'; |
| 59 | + // 8 |
| 60 | + |
| 61 | + vector<int> nums2 = {0, 1, 2}, costs2 = {1, 1, 1}; |
| 62 | + cout << Solution().minCost(nums2, costs2) << '\n'; |
| 63 | + // 2 |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments