LeetCode Entry
121. Best Time to Buy and Sell Stock
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
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
maxcandidate instead of managing themaxvariable.Complexity
- Time complexity: \(O(n)\)
- Space complexity: \(O(1)\)