In Leetcode problem 638, “Shopping Offers,” we have the following scenario:
In a supermarket, there are multiple items which you need to buy, and each item has a different price. Additionally, there are special offers that provide a discounted price for a combination of specific items.
You need to write a program to determine the minimum cost to buy exactly the desired quantities of each item.
The input is given in the following format:
price
: A list of integers where price[i]
is the price of the i-th item.special
: A list of special offers, where each offer is represented as a list of integers.
n
integers in each offer represent the quantities of items the offer covers.needs
: A list of integers representing the quantity of each item you need to buy.price = [2, 5]
special = [[3, 0, 5], [1, 2, 10]]
needs = [3, 2]
Output: 10
needs
.def shoppingOffers(price, special, needs):
def dfs(current_needs):
if tuple(current_needs) in memo:
return memo[tuple(current_needs)]
# Calculate cost without any special offers, just buying items individually
min_cost = sum(current_needs[i] * price[i] for i in range(len(price)))
for offer in special:
temp_needs = current_needs.copy()
valid_offer = True
for i in range(len(price)):
temp_needs[i] -= offer[i]
if temp_needs[i] < 0: # Cannot use this special offer
valid_offer = False
break
if valid_offer:
min_cost = min(min_cost, offer[-1] + dfs(temp_needs))
memo[tuple(current_needs)] = min_cost
return min_cost
memo = {}
return dfs(needs)
# Example usage
price = [2, 5]
special = [[3, 0, 5], [1, 2, 10]]
needs = [3, 2]
print(shoppingOffers(price, special, needs)) # Output: 14
n
be the number of items.n
.O((max_needs+1)^n)
states, where max_needs
is the maximum number of any item in the needs
.O(n)
time to calculate the cost using special offers.Thus, the time complexity is approximately O((max_needs+1)^n * n)
.
This solution should be efficient enough for the typical input sizes expected in such problems.
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?