本文主要是介绍*** Leetcode 309. Best Time to Buy and Sell Stock with Cooldown | dp,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
因为做过之前那个题,所以还是能比较快做出来的。
做法1:
dp[i][0]: 第i天卖,完成i次买和卖
dp[i][1]:第i天买,完成i-1次卖和i次买
class Solution {
public:int maxProfit(vector<int>& prices) {if (!prices.size()) return 0;// vector <int> dp(prices.size(), 0);int dp[prices.size()][2];int ans = 0;for (int i = 0; i < prices.size(); i++) {dp[i][0] = 0;dp[i][1] = INT_MIN;}for (int i = 0; i < prices.size(); i++) {if (i <= 1) {dp[i][1] = -prices[i];}for (int j = 0; j < i; j++) {if (j < i - 1)dp[i][1] = max(dp[i][1], dp[j][0] - prices[i]);dp[i][0] = max(dp[i][0], dp[j][1] + prices[i]);}ans = max(ans, dp[i][0]);// cout << "i:" << i << " d0:" << dp[i][0] << " d1:" << dp[i][1] << endl;}return ans;}
};
更自然的解法:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(By-State-Machine-Thinking)
class Solution {
public:int maxProfit(vector<int>& prices) {if (!prices.size()) return 0;vector<int> s0(prices.size(), 0);vector<int> s1(prices.size(), 0);vector<int> s2(prices.size(), 0);s0[0] = 0;s1[0] = -prices[0];s2[0] = 0;for (int i = 1; i < prices.size(); i++) {s0[i] = max(s0[i-1], s2[i-1]);s1[i] = max(s1[i-1], s0[i-1] - prices[i] );s2[i] = max(s2[i-1], s1[i-1] + prices[i]);}return max( s0[prices.size()-1], s2[prices.size()-1] );}
};
从这题和之前的卖股票的那个题,学到了状态转移表示dp的思路
这篇关于*** Leetcode 309. Best Time to Buy and Sell Stock with Cooldown | dp的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!