121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

[Easy] “Given at most one transaction, find the maximum profit from an array for which the ith element is the price of a given stock on day i. Note that you cannot sell a stock before you buy one."

Link to Leetcode

Python3:

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) <= 1:
            return 0
        
        min_price = prices[0]
        max_profit = 0
        for price in prices:
            max_profit = max(max_profit, price - min_price)
            min_price = min(price, min_price)
        
        return max_profit

Go:

func maxProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    
    low := prices[0]
    diff := 0
    
    for i, price := range prices {
        if price < low {
            // check rest of slice for biggest difference
            max := maxSlice(prices[i:])
            if (max - price) > diff {
                low = price
                diff = max - price
            }
        } else {
            if (price - low) > diff  {
                diff = price - low
            }
        }
    }
    return diff
}

func maxSlice (slice []int) int {
    if len(slice) == 0 {
        return 0
    }
    
    max := 0
    for i, elem := range slice {
        if i == 0 || elem > max {
            max = elem
        }
    }
    return max
}