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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5int buyTwoChocolates(std::vector<int>& prices, int money) {
6 std::sort(prices.begin(), prices.end());
7 int left = 0, right = prices.size() - 1;
8 int minSpent = INT_MAX;
9
10 while (left < right) {
11 int sum = prices[left] + prices[right];
12 if (sum <= money) {
13 minSpent = sum;
14 left++;
15 } else {
16 right--;
17 }
18 }
19 return (minSpent == INT_MAX) ? money : money - minSpent;
20}
21
22int main() {
23 std::vector<int> prices = {1, 2, 2};
24 int money = 3;
25 std::cout << buyTwoChocolates(prices, money) << std::endl;
26 return 0;
27}
The approach utilizes sorting followed by a two-pointer technique to determine the minimal sum of two chocolate prices that is within budget. The vector's sort function is leveraged here to enable efficient pointer manipulation.
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.
1public class BuyChocolates {
2 public static int buyTwoChocolates(int[] prices, int money) {
3 int minSpent = money + 1;
4 for (int i = 0; i < prices.length; ++i) {
5 for (int j = i + 1; j < prices.length; ++j) {
6 int sum = prices[i] + prices[j];
7 if (sum <= money && sum < minSpent) {
8 minSpent = sum;
9 }
10 }
11 }
12 return (minSpent > money) ? money : money - minSpent;
13 }
14
15 public static void main(String[] args) {
16 int[] prices = {3, 2, 3};
17 int money = 3;
18 System.out.println(buyTwoChocolates(prices, money));
19 }
20}
This Java solution follows a direct approach by evaluating all possible pairs and selecting the best choice for leftover money computation.