2706. Buy Two Chocolates
You are given an integer arrayprices
representing the prices of various chocolates in a store. You are also given a single integermoney
, 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, returnmoney
. Note that the leftover must be non-negative.
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.
MY Solv
class Solution:
def buyChoco(self, prices: List[int], money: int) -> int:
x = sum(sorted(prices)[:2])
if x > money:return money
else:return money - x
Even if there is other way to sort to select the lowest two numbers than just use built-in sort function in python, just use built-in one. In other solutions, some guy used heapq
to get lowest two numbers. Not bad, not bad.. But It is definite that heapq is slow. The built-in sort get the best result in mooooost of the time.