先放一个题解合集:力扣
121题 买卖股票的最佳时机
1.暴力思路:两层循环,遍历所有可能的收益,时间复杂度O(n²)。
2.官方题解思路:在某一天能够获得的最大收益,自然是用这天的股票价格 减去 历史上股票的最低价格。因此设置变量minPrice来记录历史上最低价格,同时要注意交易必然发生在这个最低价格出现之后,所以循环中先更新最大收益值,再更新历史最低价格。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int minPrice = 1e9;
for(int price:prices) {
ans = max(ans,price-minPrice);
minPrice = min(minPrice,price);
}
return ans;
}
};
3.用动态规划的思路理解:
若想在第i天达到最大收益,需要知道前i-1天中的最低价格,而前i-1天中的最低价格与前i-2天中最低价格有关,可以得到状态转移方程:dp[i] = min( dp[i-1], price[i] )
//dp[i]表示截止到i,价格的最低点是多少 dp[i]=min(dp[i-1],prices[i])
int max = 0;
int[] dp = new int[prices.length];
dp[0] = prices[0];
for (int i = 1; i < prices.length; i++) {
dp[i] = (dp[i - 1] < prices[i]) ? dp[i - 1] : prices[i];
max = (prices[i] - dp[i]) > max ? prices[i] - dp[i] : max;
}
return max;
122题 买卖股票的最佳时机II
1.贪心思路:并非模拟交易过程,而是直接计算正向收益之和。
若某天的价格高于前一天,则累加这一差值。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int n = prices.size();
for(int i=1;i<n;i++) {
ans += max(0,prices[i]-prices[i-1]);
}
return ans;
}
};
2.动态规划:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
//dp[i][0]表示第i天结束时,手头没有股票时的最大收益
//dp[i][1]表示第i天结束时,手头持有股票时的最大收益
int dp[n][2];
//第0天结束时
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i=1;i<n;i++) {
//第i天时手上没有股票的最大利润:1)i-1天时手头没有股票,且i天也没有;2)i-1天时手头有股票,在i天卖出
dp[i][0] = max(dp[i-1][0],dp[i-1][1]+prices[i]);
//第i天时手上持有股票的最大利润:1)i-1天时手上有股票,i天时未将其卖出;2)i-1天时手头没有股票,在i天购入
dp[i][1] = max(dp[i-1][1],dp[i-1][0]-prices[i]);
}
//最后一天一定是清仓了收益才最大
return dp[n-1][0];
}
};