标签:swap time 依赖 style turn strong color solution corn
Best Time to Buy and Sell Stock II
class Solution { public: int maxProfit(vector<int>& prices) { int res=0; for (int i=1;i<prices.size();++i){ if (prices[i]>prices[i-1]){ res += prices[i]-prices[i-1]; } } return res; } };
Best Time to Buy and Sell Stock III
比较难想到,分别记录四个状态: 1buy,1buy1sell,2buy1sell,2buy2sell。
构建四个dp数组,例如,1buy1sell[i] = max( 1buy1sell[i-1], 1buy[i-1]+prices[i] )
由于dp只依赖于上一个状态,可以压缩空间。
class Solution { public: int maxProfit(vector<int>& prices) { int n=prices.size(); int dp[2][4]; // 0 - 1 buy, 1 - 1 buy 1 sell, 2 - 2 buy 1 sell, 3 - 2 buy 2 sell for (int i=0;i<4;++i) dp[0][i] = INT_MIN/2; for (int i=0;i<n;++i){ dp[1][0] = max(dp[0][0],-prices[i]); dp[1][1] = max(dp[0][1],dp[0][0]+prices[i]); dp[1][2] = max(dp[0][2],dp[0][1]-prices[i]); dp[1][3] = max(dp[0][3],dp[0][2]+prices[i]); swap(dp[0],dp[1]); } return max(0, max(dp[0][1],dp[0][3])); } };
Best Time to Buy and Sell Stock IV
上一题的拓展,思路一样。corner case 比较多,需要特别注意。当 k > n/2 的时候,说明可以不限次数,本题就变成了 Best Time to Buy and Sell Stock II,使用 II 的方法,可以大大减少dp所需的时间和空间。
class Solution { public: int maxProfit(int k, vector<int>& prices) { if (k==0) return 0; int n=prices.size(); if (n<2) return 0; if (k>n/2){ // Best Time to Buy and Sell Stock II int ans = 0; for (int i=1; i<n; ++i) ans += max(prices[i] - prices[i-1],0); return ans; } // 0 - 1 buy, 1 - 1 buy 1 sell, 2 - 2 buy 1 sell, 3 - 2 buy 2 sell ... vector<vector<int>> dp(2,vector<int>(2*k)); for (int j=0;j<2*k;++j) dp[0][j] = INT_MIN/2; for (int i=0;i<n;++i){ dp[1][0] = max(dp[0][0],-prices[i]); for (int j=1;j<2*k;++j){ dp[1][j] = max( dp[0][j], dp[0][j-1]+(j%2==1?1:-1)*prices[i] ); } swap(dp[0],dp[1]); } int res=0; for (int j=1;j<2*k;j+=2) res = max(res,dp[0][j]); return res; } };
LeetCode 122, 123, 188. Best Time to Buy and Sell Stock II+III+IV
标签:swap time 依赖 style turn strong color solution corn
原文地址:https://www.cnblogs.com/hankunyan/p/11258505.html