luoheng
10/27/2019 - 12:23 PM

maxProfit

func maxProfit(prices []int) int {
    if len(prices) <= 1 {
        return 0
    }
    buy, sell, sum := prices[0], 0, 0
    for _, price := range prices {
        if price < sell {
            sum += sell - buy
            buy, sell = price, 0
        } else if price <= buy {
            buy = price
        } else if price >= sell {
            sell = price
        }
    }
    if sell > buy {
        sum += sell - buy
    }
    return sum
}