本文最后更新于 426 天前,其中的信息可能已经有所发展或是发生改变。
题目描述
- 给定一个数组
prices,它的第i个元素prices[i]表示一支给定股票第i天的价格。 - 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
- 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回
0。
示例1:
输入: prices = [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例2:
输入: prices = [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
提示:
- 1 <= prices.length <= 10^5
- 0 <= prices[i] <= 10^4
解题思路
第i天有持有和不持有股票两种状态,故采用二维dp数组
- 确定dp数组以及下标的含义
dp[i][0]表示第i天持有股票所得的最多现金dp[i][1]表示第i天不持有股票所得的最多现金
确定递推公式
第
i天持有股票的情况:dp[i][0],可以由买入和不买入两种情况决定- 情况1: 第
i天 买入 股票,那么第i天所得现金即第i天持有股票所得现金:-price[i] - 情况2: 第
i天 不买入 股票,那么第i天所得现金即第i-1天持有股票所得现金:dp[i-1][0] - 取上述两种情况的最大值,
dp[i][0] = max(dp[i-1][0], -price[i])
- 情况1: 第
第i天不持有股票,
dp[i][1],可以由不持有和卖出两种情况决定- 情况1: 第
i-1天不持有股票,那么保持现状,第i天所得现金即第i-1天不持有股票所得现金:dp[i-1][1] - 情况2:(i-1天持有股票) 第
i天卖出股票,第i天所得现金即第i天卖出股票所得现金与前一天股票之和:price[i] + dp[i-1][0] - 取上述两种情况的最大值,
dp[i][1] = max(dp[i-1][1], price[i] + dp[i-1][0]])
- 情况1: 第
dp数组初始化
根据递推公式:
dp[i][0] = max(dp[i-1][0], -price[i])dp[i][1] = max(dp[i-1][1], price[i] + dp[i-1][0]])
确定遍历顺序
根据递推公式可以看出,打印dp数组
dp[0][0]:表示第0天持有股票,就是第0天买入,即:dp[0][0] -= price[0] dp[0][1]:表示第0天不持有股票,即:dp[0][1] -= 0 dp[i] 都是由 dp[i-1] 推出来的,那么遍历顺序一定是从前往后遍历。
代码实现
- 核心模式
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));
// initialize the DP array
dp[0][0] = -prices[0]; // Hold the stock on the first day
dp[0][1] = 0; // No shears held on the first day
// traversal
for (int i= 1; i < len; i++){
dp[i][0] = std::max(dp[i - 1][0], -prices[i]);
dp[i][1] = std::max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
}
return dp[len - 1][1];
}
};
ACM模式
#include <iostream>
#include "dynamicPro.h"
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));
// initialize the DP array
dp[0][0] = -prices[0]; // Hold the stock on the first day
dp[0][1] = 0; // No shears held on the first day
// traversal
for (int i= 1; i < len; i++){
dp[i][0] = std::max(dp[i - 1][0], -prices[i]);
dp[i][1] = std::max(dp[i - 1][1], prices[i] + dp[i - 1][0]);
}
print2DVector(dp); // define in "dynamicPro.h"
return dp[len - 1][1];
}
};
int main(){
vector<int> case1 = {7, 1, 5, 3, 6, 4};
vector<int> case2 = {7, 6, 4, 3, 1};
Solution solution;
cout << "DP Array = " << solution.maxProfit(case1) << endl;
cout << "DP Array = " << solution.maxProfit(case2) << endl;
return 0;
}
- 输出
DP Array = [[-7, 0], [-1, 0], [-1, 4], [-1, 4], [-1, 5], [-1, 5]]
5
DP Array = [[-7, 0], [-6, 0], [-4, 0], [-3, 0], [-1, 0]]
0