Leetcode 122. Best Time to Buy and Sell Stock II

Best Time to Buy and Sell Stock II
image 6

Best Time to Buy and Sell Stock II :

每一天都可以決定買入和/或賣出股票。 在任何時候最多只能持有一股股票。 但是,可以購買它然後在同一天立即出售。找到可以實現的最大利潤。

Python

前一天比後一天的價格小,則把買賣的價差累加起來,得到最大的利潤。

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        maxprofit=0
        for i in range(1,len(prices)):
            if prices[i]>prices[i-1]:    
                maxprofit+=prices[i]-prices[i-1]

        return maxprofit

C++

如果第二天的價格比前一天高,那麼就可以在前一天買進,第二天賣出,這樣就可以獲得收益。因此,只需要計算相鄰兩天之間價格的差值,如果是正數就把它加到總的收益上。

時間複雜度為 O(n),其中 n 是股票價格數組的長度,空間複雜度為 O(1)

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