題目
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;
}
};