[LeetCode] Shopping Offers

638. Shopping Offers

In LeetCode Store, there are n items to sell. Each item has a price. However, there are some special offers, and a special offer consists of one or more different kinds of items with a sale price.

You are given an integer array price where price[i] is the price of the ith item, and an integer array needs where needs[i] is the number of pieces of the ith item you want to buy.

You are also given an array special where special[i] is of size n + 1 where special[i][j] is the number of pieces of the jth item in the ith offer and special[i][n] (i.e., the last integer in the array) is the price of the ith offer.

Return the lowest price you have to pay for exactly certain items as given, where you could make optimal use of the special offers. You are not allowed to buy more items than you want, even if that would lower the overall price. You could use any of the special offers as many times as you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
unordered_map<int, int> dp;
int makeKey(vector<int>& A) {
int res = 0;
for(int i = 0; i < A.size(); i++) {
res += A[i] * (1<<(i*4));
}
return res;
}
vector<int> helper(vector<int>& A, vector<int>& s) {
vector<int> res;
for(int i = 0; i < A.size(); i++) {
res.push_back(A[i] - s[i]);
if(res.back() < 0) return {};
}
return res;
}
public:
int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
int key = makeKey(needs);
if(dp.count(key)) return dp[key];

int res = inner_product(begin(needs), end(needs), begin(price), 0);
for(auto& s : special) {
auto nxt = helper(needs, s);
if(nxt.empty()) continue;
res = min(res, s.back() + shoppingOffers(price, special, nxt));
}
return dp[key] = res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/30/PS/LeetCode/shopping-offers/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.