LeetCode Entry

2706. Buy Two Chocolates

20.12.2023 easy 2023 kotlin

Money change after two chocolates bought

2706. Buy Two Chocolates easy blog post substack image.png

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
  }