Shopping Offers — LeetCode 638 Python Solution

MediumBit ManipulationMemoizationArrayDynamic ProgrammingBacktrackingBitmask
Problem
#638
Reading time
5 min

The problem

In LeetCode Store, there are n items to sell. Each item has a price.

Example

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.

Python solution

Python
from functools import lru_cache
from typing import List

def shoppingOffers(price: List[int], special: List[List[int]], needs: List[int]) -> int:
    n = len(price)
    filtered = []
    for sp in special:
        cost = sp[-1]
        if cost < sum(sp[i] * price[i] for i in range(n)):
            filtered.append(sp)

    @lru_cache(None)
    def dfs(state):
        state = list(state)
        best = sum(state[i] * price[i] for i in range(n))
        for sp in filtered:
            nxt = []
            for i in range(n):
                if sp[i] > state[i]:
                    break
                nxt.append(state[i] - sp[i])
            else:
                best = min(best, sp[-1] + dfs(tuple(nxt)))
        return best

    return dfs(tuple(needs))

Complexity

MeasureComplexity
TimeO(n \times k \times m^n), where n represents the types of items, and k and m respectively represent the number of bundles and the maximum demand for each type of item
SpaceO(n \times m^n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 638. Shopping Offers is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 638. Shopping Offers?
LeetCode 638. Shopping Offers is rated Medium on LeetCode.
What is the time complexity of LeetCode 638. Shopping Offers?
The Python solution on this page runs in O(n \times k \times m^n), where n represents the types of items, and k and m respectively represent the number of bundles and the maximum demand for each type of item.
What is the space complexity of LeetCode 638. Shopping Offers?
The Python solution on this page uses O(n \times m^n) auxiliary space.
What topics does LeetCode 638. Shopping Offers cover?
LeetCode 638. Shopping Offers is tagged Bit Manipulation, Memoization, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview