1、描述
买卖股票的最佳时机只买卖一次
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
2、关键字
股票,只买卖一次,
3、思路
第二天减去第一天,做差构成一个数组,然后求这个数组的最大子段和,就是结果了,因为股票会增会减,和股票的每天涨跌通吃一样,都得承受着!
4、notes
1、原型:就是求数组的最大子段和,
2、别写错了,
dp[i] = profits[i] + max(dp[i - 1],0); // 这里是前边所有的值,和0比较
5、复杂度
时间:O(N)
空间:O(N)。直接在数组上改,是O(1),但还是搞了一个profits数组。
6、code
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <=1) return 0; // 特判
vector<int>profits; // 求个差值构成数组,,然后就是求这个数组的最大子段和问题
for(int i =1; i < prices.size();i++){
profits.push_back(prices[i] - prices[i - 1]);
}
int n = profits.size();
vector<int>dp(n,profits[0]); // 构造dp数组
int res = 0;
res = max(profits[0],0); // 初始化结果值,不然会错啊
for(int i = 1; i < n; i++){
dp[i] = profits[i] + max(dp[i - 1],0); // 这里是前边所有的值,和0比较
res = max(res,dp[i]);
}
return res;
}
};
7、这只股票可以买卖多次
那就把上升的子段都加起来
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
for(int i = 1; i < prices.size(); i++){
if ( prices[i] > prices[i - 1]) {
res += prices[i] - prices[i - 1];
}
}
return res;
}
};