-
题目:
一个数组prices的每个元素prices[ i ] 表示一支特定股票当天的价格;
不能同时持有多只股票,只能卖出去才能再买;
求最高利润; -
思路:
股票系列问题是典型的DP问题;
但本题还可以用贪心,更简单;
1.DP:O(n),O(1)
维护两个变量:持有股票的最多钱 和 不持有股票的最多钱
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
int n = prices.size();
int hold_stack = (-1) * prices[0], nohold_stack = 0;
for (int i = 1; i < n; ++i) {
hold_stack = max(hold_stack, nohold_stack - prices[i]);
nohold_stack = max(nohold_stack, hold_stack + prices[i]);
}
return nohold_stack;
}
};
2.贪心:O(n),O(1)
这道买卖股票题是最简单的,没有手续费。因此只累计递增区间即可;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
int n = prices.size();
for (int i = 1; i < n; ++i) {
int curDif = prices[i] - prices[i - 1];
if (curDif > 0) res += curDif;
}
return res;
}
};
- 总结:
股票问题右很多题,目前只刷过两题,等刷完本系列再统一总结;