【Leetcode】買賣股票-貪心算法


題目:

給定一個數組,它的第 i 個元素是一支給定股票第 i 天的價格。

設計一個算法來計算你所能獲取的最大利潤。你可以盡可能地完成更多的交易(多次買賣一支股票)。

注意:你不能同時參與多筆交易(你必須在再次購買前出售掉之前的股票)。

 

 

思路:

采用貪心算法,如果當天股票的價格 pi 大於等於前一天的股票價格 pi-1 則持續持有。如果低於前一天的價格,則在前一天就拋售股票。

時間復雜度:O(N)。從頭遍歷每一天的股票價格。

空間復雜度:O(1)。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buyin = 0, keep = 1, profit = 0;
        int len = prices.size();
        
        while(buyin+keep < len) {
            int buyP = prices[buyin];
            
            for(keep; keep < (len-buyin); keep++) {
                if(prices[buyin+keep-1] > prices[buyin+keep]) {
                    if(keep > 1) {
                        profit = profit + (prices[buyin+keep-1] - buyP);
                    }
                    
                    break;
                }
                
                else {
                    if(buyin+keep+1 == len)
                        profit = profit + (prices[buyin+keep] - buyP);
                }
            }
            
            buyin = buyin+keep;
            keep = 1;
        }
        return profit;
    }
};

 

另一種思路。每一天都盯盤,只要當天利潤P>0,買賣股票,利潤增加。如果當天利潤P≤0,不進行操作。

時間復雜度和空間復雜度同上,但是代碼實現過程簡化很多。耗時非常少。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int totalProfite = 0;
        for (size_t i = 1; i < prices.size(); i++)
        {
            if (prices[i - 1] < prices[i])
                totalProfite += (prices[i]-prices[i-1]);
        }
        return totalProfite;
    }
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM