Leetcode 2706. Buy Two Chocolates
You are given an integer array, prices
, representing the prices of various chocolates in a store. You also have a certain amount of money in your wallet. You need to find out whether you can buy exactly two different chocolates such that the total cost does not exceed the amount of money you have. Return true
if you can buy the chocolates and false
otherwise.
prices
array? (e.g., 1 to 1000)prices
array?prices
array has fewer than 2 elements?For the sake of this solution, let’s assume:
prices
array is between 0 and 10^4.To solve this problem efficiently, we can use a two-pointer technique:
prices
array.left
) and one at the end (right
) of the sorted array.prices
at these pointers:
true
.right
pointer to the left to reduce the sum.left
pointer to the right to increase the sum.left
pointer is less than the right
pointer.The idea is to find any two distinct elements whose sum is less than or equal to the given amount of money.
#include <iostream>
#include <vector>
#include <algorithm>
bool canBuyTwoChocolates(std::vector<int>& prices, int money) {
int n = prices.size();
// Early return if there are less than 2 chocolates to buy
if (n < 2) {
return false;
}
// Sort the price array
std::sort(prices.begin(), prices.end());
// Two pointers technique
int left = 0;
int right = n - 1;
while (left < right) {
int sum = prices[left] + prices[right];
if (sum <= money) {
return true; // Found two chocolates within the budget
} else if (sum > money) {
--right; // Decrease sum by moving right pointer to the left
} else {
++left; // Increase sum by moving left pointer to the right
}
}
// If we exit the loop, it means we couldn't find such a pair
return false;
}
// Example to test the function
int main() {
std::vector<int> prices = {12, 7, 22, 10, 5};
int money = 17;
if (canBuyTwoChocolates(prices, money)) {
std::cout << "Yes, can buy two chocolates" << std::endl;
} else {
std::cout << "No, cannot buy two chocolates" << std::endl;
}
return 0;
}
prices
array to apply the two-pointer technique efficiently.left
at the beginning and right
at the end of the sorted array.Thus, the overall time complexity is (O(n \log n)), where (n) is the number of elements in the prices
array. This is efficient for the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?