121. Best Time to Buy and Sell Stock
买卖股票的最佳时机
You are given an array prices where prices[i] is the price of a given stock on the i^th day.
你将获得一个数组 prices ,其中 prices[i] 表示该股票在第 i^th 天的价格。
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
你希望在某一天 买入一支股票,并选择 未来某一天 卖出该股票,以获得最大利润。
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
返回你能从这次交易中获取的最大利润。如果你无法获得任何利润,则返回 0 。
Example 1: 示例 1
Input: prices = [7,1,5,3,6,4]
utput: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Ways of solving a problem 解题思路
- 记录最低价格和可以获得的最大利润
- 若当前价格小于最低价格,则更新当前最低价格
- 若当前价格大于最低价格,则计算可以获得的利润,若大于当前最大利润,则更新最大利润
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minPrices = prices[0];
int getMaxProfit = 0;
for (auto&& price : prices) {
if (minPrices >= price) {
minPrices = price;
} else {
getMaxProfit = std::max(getMaxProfit, price - minPrices);
}
}
return getMaxProfit;
}
};
动态规划解法
dp[i][0]记录第i天结束时,不持有股票获得的最大利润dp[i][1]记录第i天结束时,持有股票获得的最大利润- 初始条件
- dp[i][0] = 0 (没有买入也没有卖出)
- dp[i][1] = -prices[i] (当前持有股票只有买入)
- 递推公式
- 不持有股票,要么是昨天已经卖出,要么是今天卖出
- dp[i][0] = std::max(dp[i - ][0], dp[i - ][1] + prices[i]);
- 持有股票,要么是昨天一直持有,要么是今天买入
- dp[i][1] = std::max(dp[i - 1][1], -prices[i]);
- 不持有股票,要么是昨天已经卖出,要么是今天卖出
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int n = prices.size();
vector<vector<int>> dp(n, vector<int>(2, 0));
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < n; ++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]);
}
// 最后一天不持有股票的利润
return dp[n - 1][0];
}
};

浙公网安备 33010602011771号