Skip to content

122. Best Time to Buy and Sell Stock II

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

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

    let buy = prices[0]
    let prev = buy
    let profit = 0

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

    profit += prev - 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]
        prev = buy
        profit = 0

        for price in prices:
            if price > prev:
                prev = price
            else:
                profit += prev - buy
                prev = buy = price

        profit += prev - buy

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

	buy := prices[0]
	prev := buy
	profit := 0

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

	profit += prev - buy
	return profit
}