LeetCode Entry

121. Best Time to Buy and Sell Stock

25.02.2023 easy 2023 kotlin

we can just use current value as a max candidate instead of managing the max variable.

121. Best Time to Buy and Sell Stock easy

blog post


fun maxProfit(prices: IntArray): Int {
    var min = prices[0]
    var profit = 0
    prices.forEach {
        if (it < min) min = it
        profit = maxOf(profit, it - min)
    }
    return profit
}

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/129

Intuition

Max profit will be the difference between max and min. One thing to note, the max must follow after the min.

Approach

  • we can just use current value as a max candidate instead of managing the max variable.

    Complexity

  • Time complexity: \(O(n)\)
  • Space complexity: \(O(1)\)