Problem

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.

Examples

Example 1

1
2
3
4
5
6
Input: price = [2,5], special = [[3,0,5],[1,2,10]], needs = [3,2]
Output: 14
Explanation: There are two kinds of items, A and B. Their prices are $2 and $5 respectively. 
In special offer 1, you can pay $5 for 3A and 0B
In special offer 2, you can pay $10 for 1A and 2B. 
You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.

Example 2

1
2
3
4
5
6
Input: price = [2,3,4], special = [[1,1,0,4],[2,2,1,9]], needs = [1,2,1]
Output: 11
Explanation: The price of A is $2, and $3 for B, $4 for C. 
You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C. 
You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C. 
You cannot add more items, though only $9 for 2A ,2B and 1C.

Constraints

  • n == price.length == needs.length
  • 1 <= n <= 6
  • 0 <= price[i], needs[i] <= 10
  • 1 <= special.length <= 100
  • special[i].length == n + 1
  • 0 <= special[i][j] <= 50
  • The input is generated that at least one of special[i][j] is non-zero for 0 <= j <= n - 1.

Solution

Method 1 – Memoized DFS (Backtracking)

Intuition

We want the minimum cost to buy all needed items, using special offers optimally. Since each offer can be used multiple times and the state space is small, we can use DFS with memoization to try all combinations efficiently.

Approach

  1. Use a recursive function to try all possible ways to fulfill the needs.
  2. For each call, try:
    • Buying items individually (no offer).
    • For each special offer, check if it can be applied (doesn’t exceed needs), then apply it and recurse.
  3. Use memoization to cache results for each needs state.
  4. Return the minimum cost found.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
    unordered_map<string, int> memo;
    int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        return dfs(price, special, needs);
    }
    int dfs(vector<int>& price, vector<vector<int>>& special, vector<int>& needs) {
        string key;
        for (int n : needs) key += to_string(n) + ",";
        if (memo.count(key)) return memo[key];
        int ans = 0;
        for (int i = 0; i < needs.size(); ++i) ans += price[i] * needs[i];
        for (auto& offer : special) {
            bool valid = true;
            vector<int> nxt = needs;
            for (int i = 0; i < needs.size(); ++i) {
                if (nxt[i] < offer[i]) valid = false;
                nxt[i] -= offer[i];
            }
            if (valid) ans = min(ans, offer.back() + dfs(price, special, nxt));
        }
        return memo[key] = ans;
    }
};
 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
32
33
34
func shoppingOffers(price []int, special [][]int, needs []int) int {
    memo := map[string]int{}
    var dfs func([]int) int
    dfs = func(needs []int) int {
        key := fmt.Sprint(needs)
        if v, ok := memo[key]; ok {
            return v
        }
        ans := 0
        for i := range needs {
            ans += price[i] * needs[i]
        }
        for _, offer := range special {
            valid := true
            nxt := make([]int, len(needs))
            copy(nxt, needs)
            for i := range needs {
                if nxt[i] < offer[i] {
                    valid = false
                }
                nxt[i] -= offer[i]
            }
            if valid {
                cost := offer[len(offer)-1] + dfs(nxt)
                if cost < ans {
                    ans = cost
                }
            }
        }
        memo[key] = ans
        return ans
    }
    return dfs(needs)
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
    Map<String, Integer> memo = new HashMap<>();
    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        return dfs(price, special, needs);
    }
    int dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        String key = needs.toString();
        if (memo.containsKey(key)) return memo.get(key);
        int ans = 0;
        for (int i = 0; i < needs.size(); ++i) ans += price.get(i) * needs.get(i);
        for (List<Integer> offer : special) {
            boolean valid = true;
            List<Integer> nxt = new ArrayList<>(needs);
            for (int i = 0; i < needs.size(); ++i) {
                if (nxt.get(i) < offer.get(i)) valid = false;
                nxt.set(i, nxt.get(i) - offer.get(i));
            }
            if (valid) ans = Math.min(ans, offer.get(offer.size()-1) + dfs(price, special, nxt));
        }
        memo.put(key, ans);
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    val memo = mutableMapOf<List<Int>, Int>()
    fun shoppingOffers(price: List<Int>, special: List<List<Int>>, needs: List<Int>): Int {
        return dfs(price, special, needs)
    }
    fun dfs(price: List<Int>, special: List<List<Int>>, needs: List<Int>): Int {
        memo[needs]?.let { return it }
        var ans = needs.indices.sumOf { price[it] * needs[it] }
        for (offer in special) {
            val nxt = needs.toMutableList()
            var valid = true
            for (i in needs.indices) {
                if (nxt[i] < offer[i]) valid = false
                nxt[i] -= offer[i]
            }
            if (valid) ans = minOf(ans, offer.last() + dfs(price, special, nxt))
        }
        memo[needs] = ans
        return ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def shoppingOffers(price: list[int], special: list[list[int]], needs: list[int]) -> int:
    memo: dict[tuple[int, ...], int] = {}
    def dfs(needs: tuple[int, ...]) -> int:
        if needs in memo:
            return memo[needs]
        ans = sum(p * n for p, n in zip(price, needs))
        for offer in special:
            nxt = tuple(n - o for n, o in zip(needs, offer[:-1]))
            if all(x >= 0 for x in nxt):
                ans = min(ans, offer[-1] + dfs(nxt))
        memo[needs] = ans
        return ans
    return dfs(tuple(needs))
 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
use std::collections::HashMap;
impl Solution {
    pub fn shopping_offers(price: Vec<i32>, special: Vec<Vec<i32>>, needs: Vec<i32>) -> i32 {
        fn dfs(price: &Vec<i32>, special: &Vec<Vec<i32>>, needs: Vec<i32>, memo: &mut HashMap<Vec<i32>, i32>) -> i32 {
            if let Some(&v) = memo.get(&needs) { return v; }
            let mut ans = 0;
            for i in 0..needs.len() { ans += price[i] * needs[i]; }
            for offer in special {
                let mut nxt = needs.clone();
                let mut valid = true;
                for i in 0..needs.len() {
                    if nxt[i] < offer[i] { valid = false; }
                    nxt[i] -= offer[i];
                }
                if valid {
                    let cost = offer[offer.len()-1] + dfs(price, special, nxt, memo);
                    if cost < ans { ans = cost; }
                }
            }
            memo.insert(needs, ans);
            ans
        }
        let mut memo = HashMap::new();
        dfs(&price, &special, needs, &mut memo)
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    memo = new Map<string, number>();
    shoppingOffers(price: number[], special: number[][], needs: number[]): number {
        return this.dfs(price, special, needs);
    }
    dfs(price: number[], special: number[][], needs: number[]): number {
        const key = needs.join(",");
        if (this.memo.has(key)) return this.memo.get(key)!;
        let ans = price.reduce((acc, p, i) => acc + p * needs[i], 0);
        for (const offer of special) {
            const nxt = needs.map((n, i) => n - offer[i]);
            if (nxt.every(x => x >= 0)) {
                ans = Math.min(ans, offer[offer.length-1] + this.dfs(price, special, nxt));
            }
        }
        this.memo.set(key, ans);
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(s * m^n), where s is the number of specials, m is the max need, n is the number of items. The state space is small due to constraints.
  • 🧺 Space complexity: O(m^n), for memoization.

Method 2 -

Code

Complexity

  • Time: O(nnnxxxnnn)
  • Space: O(nnnxxx)