Sort the array of prices and use a two-pointer technique to find the two cheapest chocolates that can be bought such that their sum is less than or equal to the given amount of money. This approach helps efficiently find a solution by reducing the problem space through sorting.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) as the sorting is in-place.
1function buyTwoChocolates(prices, money) {
2 prices.sort((a, b) => a - b);
3 let left = 0, right = prices.length - 1;
4 let minSpent = Infinity;
5
6 while (left < right) {
7 const sum = prices[left] + prices[right];
8 if (sum <= money) {
9 minSpent = sum;
10 left++;
11 } else {
12 right--;
13 }
14 }
15 return minSpent === Infinity ? money : money - minSpent;
16}
17
18console.log(buyTwoChocolates([1, 2, 2], 3));
Sorting is performed on the prices array, and two pointers scan through possible pairs. The logic ensures the cheapest viable pair is chosen within the monetary constraint.
In this approach, check all possible pairs of chocolate prices. If a pair's sum is within the available money and minimal, update the result. Although this approach is less efficient, it is a simple and direct way to solve the problem given the constraints.
Time Complexity: O(n^2) due to the nested loop.
Space Complexity: O(1) with a few extra variables.
1function buyTwoChocolates(prices, money) {
2 let minSpent = money + 1;
3 for (let i = 0; i < prices.length; i++) {
4 for (let j = i + 1; j < prices.length; j++) {
5 const sum = prices[i] + prices[j];
6 if (sum <= money && sum < minSpent) {
7 minSpent = sum;
8 }
9 }
10 }
11 return minSpent > money ? money : money - minSpent;
12}
13
14console.log(buyTwoChocolates([3, 2, 3], 3));
In JavaScript, every pair of chocolates is evaluated using nested loops, checking their contribution to minimal leftover money after purchase.