leetcode-122-线性DP-买卖股票的最佳时机II 发表于 2020-04-24 | 分类于 数据结构与算法 题目 解法123456789101112131415161718192021222324252627282930313233343536373839// 动态规划class Solution {public: int maxProfit(vector<int>& prices) { if(prices.empty() || prices.size() == 1) return 0; // dp[i][0]=x,表示今天没有持有股票,当前最大利润为x // dp[i][1]=x,表示今天持有股票,当前最大利润为x vector<vector<int>> dp(prices.size(), vector<int>(2, 0));、 dp[0][0] = 0; dp[0][1] = -prices[0]; for(int i = 1; i < prices.size(); ++i){ // 状态转移 dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i]); dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i]); } return dp[prices.size() - 1][0]; }};// 动态规划,优化空间复杂度class Solution {public: int maxProfit(vector<int>& prices) { int n = prices.size(); if(prices.empty() || n == 1) return 0; int dp_i_0 = 0; int dp_i_1 = -prices[0]; for(int i = 1; i < n; ++i){ int temp = dp_i_0; dp_i_0 = max(dp_i_0, dp_i_1 + prices[i]); dp_i_1 = max(dp_i_1, temp - prices[i]); } return dp_i_0; }};