LeetCode Entry
2706. Buy Two Chocolates
Money change after two chocolates bought
2706. Buy Two Chocolates easy
blog post
substack

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/445
Problem TLDR
Money change after two chocolates bought
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(1)\)
Code
fun buyChoco(prices: IntArray, money: Int): Int {
var (a, b) = Int.MAX_VALUE to Int.MAX_VALUE
for (x in prices)
if (x < a) a = x.also { b = a }
else if (x < b) b = x
return (money - a - b).takeIf { it >= 0 } ?: money
}