Leetcode

122. Best Time to Buy and Sell Stock II

Leeter 2021. 11. 10. 11:39

Description:

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

'''
[1] brute force - recursive and calculate all possibility)

code::
def maxProfit(self, prices: List[int]) -> int:
    return self.calcProfit(prices,0,len(prices)-1)

def calcProfit(self, prices, start, end):
    if start>=end:
        return 0

    profit=0
    for i in range(start,end):
        for j in range(i+1,end+1):
            if prices[j]>prices[i]:
                curProfit=prices[j]-prices[i]    # cur inteval profit
                curProfit+=self.calcProfit(prices,start,i-1)+self.calcProfit(prices,j+1,end) #both sides
                profit=max(profit,curProfit)
    return profit
                    
-T/C: O(n^n)
-S/C: O(n)
'''
'''
[2] geometry approach)

idea::
max_profit will be sum(localMaxPrice-localMinPrice).

code::
def maxProfit(self, prices: List[int]) -> int:

    local_min,local_max=0,0
    profit=0

    i=0
    while i<len(prices)-1:
        while i<len(prices)-1 and prices[i]>=prices[i+1]:
            i+=1
        local_min=prices[i]

        while i<len(prices)-1 and prices[i]<=prices[i+1]:
            i+=1
        local_max=prices[i]
        profit+=local_max-local_min

    return profit
    
-T/C: O(n)
-S/C: O(1)
'''
'''
[3] geometry approach - optimization)

code::
def maxProfit(self, prices: List[int]) -> int:
    profit=0

    for i in range(len(prices)-1):
        if prices[i+1]-prices[i]>0:
            profit+=prices[i+1]-prices[i]

    return profit
    
-T/C: O(n)
-S/C: O(1)
'''

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        
        local_min,local_max=0,0
        profit=0
        
        i=0
        while i<len(prices)-1:
            while i<len(prices)-1 and prices[i]>=prices[i+1]:
                i+=1
            local_min=prices[i]
            
            while i<len(prices)-1 and prices[i]<=prices[i+1]:
                i+=1
            local_max=prices[i]
            profit+=local_max-local_min
            
        return profit