给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
方法一:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int buy = prices[0]; int pre = 1; int profit =0;
for (pre;pre<prices.size();pre++){
if(buy>prices[pre]){
buy = prices[pre];
}else if(buy<prices[pre]){
if(profit<(prices[pre]-buy)){
profit = prices[pre]-buy;
}
}
}
return profit;
}
};
方法二:遍历一遍数组,用一个变量记录历史最低点。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minprice = 1e9; int maxprofit = 0;
for(int price:prices){
maxprofit = max(maxprofit,price-minprice);
minprice = min(price,minprice);
}
return maxprofit;
}
};