DEV Community

hamza72x
hamza72x

Posted on • Updated on

[Grind 169] 4. Best Time to Buy and Sell Stock

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

Solution:

func maxProfit(prices []int) int {
    var profit = 0
    var n = len(prices)
    var left = 0
    var right = 1

    for right < n {
        if prices[right] > prices[left] {
            var diff = prices[right] - prices[left]
            if diff > profit {
                profit = diff 
            }
        } else {
            left = right
        }

        right++
    }

    return profit
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)