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.
For example:
If prices = [1, 2, 2]
and money = 3
, the output should be 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.
If prices = [3, 2, 3]
and money = 3
, the output should be 3
.
Explanation: You cannot buy 2 chocolates without going in debt, so we return 3.
The simplest approach is to iterate through all possible pairs of chocolates, calculate the sum of their prices, and check if buying them leaves a non-negative amount of money. We keep track of the minimum sum that satisfies this condition.
def solve_naive(prices, money):
min_cost = float('inf')
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
cost = prices[i] + prices[j]
if money - cost >= 0:
min_cost = min(min_cost, cost)
if min_cost == float('inf'):
return money
else:
return money - min_cost
O(n^2), where n is the number of chocolates (length of prices
array), because of the nested loops.
O(1), as we are only using a constant amount of extra space.
To optimize, we can find the two cheapest chocolates. Sort the array, and the first two elements are the cheapest.
def solve_optimal(prices, money):
prices.sort()
cost = prices[0] + prices[1]
if money - cost >= 0:
return money - cost
else:
return money
O(n log n) due to the sorting of the prices
array.
O(1) or O(n) depending on the sorting algorithm implementation. Some sorting algorithms like quicksort can take O(log n) space, while others like merge sort can take O(n) space.