題目描述
已知一個數組,第i個元素表示第i天股票的價格,你只能進行一次交易(買賣各一次),設計算法找出最大收益
測試樣例
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大收益 = 6-1 = 5 (不是7-1 = 6,因爲先買後賣,7買,1買虧了6)
Input: [7, 6, 4, 3, 1]
Output: 0
最大收益爲0
詳細分析
初看非常簡單,遍歷數組,每次選擇一個元素,找到這個元素後面的數組的最大值,計算差值,和當前最大收益比較即可,就像這樣: [7,1,5,3,6,4] 當前7,後面最大6,收益-1 [7,1,5,3,6,4] 當前1,後面最大6,收益5 [7,1,5,3,6,4] 當前5,後面最大6,收益1 如此繼續找到即可。 不過這種方法會超時,稍微改變一下,現在不止保持最大收益,還保存最低價格,如果當天價格更低,就刷新最小价格(買),同時如果當天價格減去最小价格的收益最大,就刷新最大價格(賣),過程如下:
[7,1,5,3,6,4] minPrice=INT_MAX,maxProfit=0
=> minPrice=7,maxProfit=0
[7,1,5,3,6,4] minPrice=7,maxProfit=0
=> minPrice=1,maxProfit=0
[7,1,5,3,6,4] minPrice=1,maxProfit=0
=> minPrice=1,maxProfit=4
[7,1,5,3,6,4] minPrice=1,maxProfit=4
=> minPrice=1,maxProfit=4
[7,1,5,3,6,4] minPrice=1,maxProfit=4
=> minPrice=1,maxProfit=5
[7,1,5,3,6,4] minPrice=1,maxProfit=5
=> minPrice=1,maxProfit=5
算法實現
- 方法1:Time Limit Exceeded
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
for(auto start=prices.begin();start!=prices.end();start++){
int buy = *start;
int sell = *std::max_element(start,prices.end());
if((sell - buy)>profit){
profit = sell-buy;
}
}
return profit;
}
};
- 方法2: Accepted
class Solution{
public:
int maxProfit(vector<int> &prices){
int profit = 0;
int minBuy = std::numeric_limits<int>::max();
for(int i=0;i<prices.size();i++){
//buy it if current price is less than minimum prices yet
if(prices[i]<minBuy){
minBuy = prices[i];
}
//sell it if current profit got optimally
if((prices[i]-minBuy)>profit){
profit = prices[i]-minBuy;
}
}
return profit;
}
};