Leetcode Problem 2706. Buy Two Chocolates

2706. Buy Two Chocolates

Leetcode Solutions

Approach: One Pass

  1. Initialize two variables, minimum and second_minimum, with the first two prices in the array after comparing them.
  2. Iterate through the array starting from the third element.
    • If the current price is less than minimum, update second_minimum to minimum and minimum to the current price.
    • Else if the current price is less than second_minimum, update second_minimum to the current price.
  3. After the iteration, calculate the sum of minimum and second_minimum as min_cost.
  4. If min_cost is less than or equal to money, return money - min_cost as the leftover money.
  5. If min_cost is greater than money, return money as there is no way to buy two chocolates without going into debt.
UML Thumbnail

Approach: Check Every Pair of Chocolate

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...