题目
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
翻译
假设说你有一个数组,第i个元素表示第i天股票价格。
如果仅允许你最多交易一次(比如:交易:买一次和卖一次股票)。设计一个算法,求出最大收益
思路
我们可以形象的考虑,题目求得就是最大的坡度。
用pri表示当前最低的价格。然后如果当前价格大于pri。则计算收益,更新max(最大收益)。如果小于pri。则更新价格。
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 0){
return 0;
}
int max = 0;
int pri = prices[0];
for(int i = 0; i < len; i++){
if(prices[i] > pri){
//判断当前收益是否大于max
if(prices[i] - pri > max){
max = prices[i] - pri;
}
}else{
//记录最低买入
pri = prices[i]; //当前价格小于之前的买入价格,则更新买入价格。
}
}
return max;
}
};
优化代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
int maxProfit = 0;
int pri = INT_MAX;
for(int i = 0; i < len; i++){
maxProfit = std::max((prices[i]-pri),maxProfit);
pri = std::min(prices[i],pri);
}
return maxProfit;
}
};

本文介绍了一个简单的算法,用于解决股票交易中如何通过一次买卖操作获得最大利润的问题。算法通过跟踪历史最低价并计算当前价格与最低价之差来找出最大收益。

被折叠的 条评论
为什么被折叠?



