[LeetCode] Buy Two Chocolates

2706. Buy Two Chocolates

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.

1
2
3
4
5
6
7
8
9
class Solution {
public:
int buyChoco(vector<int>& prices, int money) {
sort(begin(prices), end(prices));
int res = money - prices[0] - prices[1];
return res >= 0 ? res : money;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/28/PS/LeetCode/buy-two-chocolates/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.