Skip to content

121. Best Time to Buy and Sell Stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

js
/**
 * @param {number[]} prices
 * @return {number}
 */
function maxProfit(prices) {
    if (!prices.length) {
        return 0
    }

    let buy = prices[0]
    let profit = 0

    for (let price of prices) {
        if (price < buy) {
            buy = price
        } else if (price - buy > profit) {
            profit = price - buy
        }
    }

    return profit
}
py
class Solution(object):

    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0

        buy = prices[0]
        profit = 0

        for price in prices:
            if price < buy:
                buy = price
            elif price - buy > profit:
                profit = price - buy

        return profit
go
func maxProfit(prices []int) int {
	if len(prices) == 0 {
		return 0
	}

	buy := prices[0]
	profit := 0

	for _, price := range prices {
		if price < buy {
			buy = price
		} else if price-buy > profit {
			profit = price - buy
		}
	}

	return profit
}