121 买卖股票的最佳时机
和之前那个题一样也是判断拿和不拿两种状态,递推公式自己写错了; 这里有点搞笑我刚好写成了这一天另一个题目的122的递推公式就是把-price[i] 加上了之前的盈利总和。 121这么写不能通过; 122那道题之前在贪心做过了。 不过想一想如果按照121题目的说明,只选取一次,那么之前的时候手上现金肯定为0
class Solution {
public:
int maxProfit(vector<int>& prices) {
int height = prices.size();
vector<vector<int>> dp(height, vector<int>(2)); //第一个数是行,第二个数是列
dp[0][0] = - prices[0];
dp[0][1] = 0;
for (int i = 1; i < prices.size(); i++) {
//dp[i][0] = max(dp[i - 1][0], prices[i] + dp[i - 1][1]); //0为这一天持有股票最大现金
//dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]); //1这一天不持有股票最大现金
dp[i][0] = max(dp[i - 1][0], - prices[i]); //今天才买的股票持有现金为-prices[i]
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
}
return max(dp[height - 1][0], dp[height - 1][1]);
}
};