121. 买卖股票的最佳时机
- 买卖股票的最佳时机
视频讲解:https://www.bilibili.com/video/BV1Xe4y1u77q
https://programmercarl.com/0121.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BA.html
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len==0)
return 0;
vector<vector<int>> dp(2,vector<int>(2));
dp[0][0]-=prices[0];
dp[0][1]=0;
for(int i=1;i<len;i++) {
dp[i%2][0] = max(dp[(i-1)%2][0],-prices[i]);
dp[i%2][1] = max(dp[(i-1)%2][1],prices[i]+dp[(i-1)%2][0]);
}
return dp[(len-1)%2][1];
}
};
122.买卖股票的最佳时机II
122.买卖股票的最佳时机II
视频讲解:https://www.bilibili.com/video/BV1D24y1Q7Ls
https://programmercarl.com/0122.%E4%B9%B0%E5%8D%96%E8%82%A1%E7%A5%A8%E7%9A%84%E6%9C%80%E4%BD%B3%E6%97%B6%E6%9C%BAII%EF%BC%88%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%EF%BC%89.html
解析就不写了…
//遇上一题的区别:可以多次买和卖,第i天买的钱就变成了dp[i-1][1]-prices[i]
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len==0)
return 0;
vector<vector<int>> dp(len,vector<int>(2));
dp[0][0]-=prices[0];
dp[0][1]=0;
for(int i=1;i<len;i++) {
//遇上一题的区别:可以多次买和卖,第i天买的钱就变成了dp[i-1][1]-prices[i]
dp[i][0] = max(dp[i-1][0], dp[i-1][1]-prices[i]);
dp[i][1] = max(dp[i-1][1], prices[i]+dp[i-1][0]);
}
return dp[len-1][1];
}
};