LeetCode 2706. Buy Two Chocolates Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2706. Buy Two Chocolates

Description

You are given an integer array prices representing the prices of various chocolates in a store. You are also given a single integer money, which represents your initial amount of money.

You must buy exactly two chocolates in such a way that you still have some non-negative leftover money. You would like to minimize the sum of the prices of the two chocolates you buy.

Return the amount of money you will have leftover after buying the two chocolates. If there is no way for you to buy two chocolates without ending up in debt, return money. Note that the leftover must be non-negative.

 

Example 1:

Input: prices = [1,2,2], money = 3
Output: 0
Explanation: Purchase the chocolates priced at 1 and 2 units respectively. You will have 3 - 3 = 0 units of money afterwards. Thus, we return 0.

Example 2:

Input: prices = [3,2,3], money = 3
Output: 3
Explanation: You cannot buy 2 chocolates without going in debt, so we return 3.

 

Constraints:

  • 2 <= prices.length <= 50
  • 1 <= prices[i] <= 100
  • 1 <= money <= 100

Solutions

Solution 1: Sorting

We can sort the prices of the chocolates in ascending order, and then add the first two prices to get the minimum cost cost of buying two chocolates. If this cost is greater than the money we have, then we return money. Otherwise, we return money - cost.

The time complexity is O(n × log n), and the space complexity is O(log n). Where n is the length of the array prices.

PythonJavaC++GoTypeScriptRust
class Solution: def buyChoco(self, prices: List[int], money: int) -> int: prices.sort() cost = prices[0] + prices[1] return money if money < cost else money - cost(code-box)

Solution 2: One-pass Traversal

We can find the two smallest prices in one pass, and then calculate the cost.

The time complexity is O(n), where n is the length of the array prices. The space complexity is O(1).

PythonJavaC++GoTypeScriptRust
class Solution: def buyChoco(self, prices: List[int], money: int) -> int: a = b = inf for x in prices: if x < a: a, b = x, a elif x < b: b = x cost = a + b return money if money < cost else money - cost(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !