121. 买卖股票的最佳时机
给定一个数组 prices
,它的第 i
个元素 prices[i]
表示一支给定股票第 i
天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
。
维护两个变量
一个是到目前为止所遇到的最低股票价格
minPrice
另一个是到目前为止能获得的最大利润
maxProfit
遍历价格数组
prices
,对于每一个价格,首先计算如果在这一天卖出股票能得到的利润(当前价格减去之前的最低价格)然后更新
maxProfit
接着,更新
minPrice
为当前价格和之前minPrice
的较小值
/*
* @lc app=leetcode.cn id=121 lang=cpp
*
* [121] 买卖股票的最佳时机
*/
// @lc code=start
class Solution {
public:
int maxProfit(vector& prices) {
if (prices.empty()) return 0;
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > minPrice) {
maxProfit = max(maxProfit, prices[i] - minPrice);
} else {
minPrice = prices[i];
}
}
return maxProfit;
}
};
// @lc code=end
122. 买卖股票的最佳时机 II
给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
解决方案是遍历价格数组
prices
,并且只要发现第二天的价格比第一天高,就将这个差值加到总利润中。这样,通过累计所有的正差值(即所有上涨的利润),就能得到可能的最大利润。
/*
* @lc app=leetcode.cn id=122 lang=cpp
*
* [122] 买卖股票的最佳时机 II
*/
// @lc code=start
class Solution {
public:
int maxProfit(vector& prices) {
int maxProfit = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
};
// @lc code=end