Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售賣時(動態規劃,數組,模擬)

題目描述

已知一個數組,第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;
    }
};
發佈了63 篇原創文章 · 獲贊 51 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章