您的位置:首页 > 编程语言 > C语言/C++

LeetCode - 121. Best Time to Buy and Sell Stock - 思路详解 - C++

2017-01-16 22:40 471 查看

题目

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: