Best Time to Buy and Sell Stock

ID: 121; easy

Solution 1

func maxProfit(prices []int) int {
    start, profit := prices[0], 0
    for i := 0; i < len(prices); i++ {
        diff := prices[i] - start
        if diff > profit {
            profit = diff
        } else if diff < 0 {
            start = prices[i]
        }
    }
    return profit
}

Last updated