Shopping Offers LeetCode Solution

Last updated on February 12th, 2025 at 02:36 am

Here, we see a Shopping Offers LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Depth First Search, Dynamic Programming

Companies

Google

Level of Question

Medium

Shopping Offers LeetCode Solution

Shopping Offers LeetCode Solution

1. Problem Statement

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.

Example 1:
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:
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.

2. Coding Pattern Used in Solution

The coding pattern used in all the provided implementations is “0/1 Knapsack”. This is because the problem involves making decisions about whether to include or exclude certain “offers” (special discounts) to minimize the total cost while satisfying the “needs” (constraints).

This is analogous to the 0/1 Knapsack problem, where you decide whether to include or exclude items to maximize or minimize a value under certain constraints.

3. Code Implementation in Different Languages

3.1 Shopping Offers C++

class Solution {
private:
    int ex(int ind, vector<int> ds, vector<int> &price, vector<vector<int>> &offer, vector<int> &need,  map<int,map<vector<int>,int>> &dp){
        if(ind==offer.size()){
            int tot=0;
            for(int i=0; i<need.size(); i++){
                tot+=(need[i]-ds[i])*price[i];
            }
            return tot;
        }
        if(dp.find(ind)!=dp.end() && dp[ind].find(ds)!=dp[ind].end()){
            return dp[ind][ds];
        }
        int offer_notTake=ex(ind+1,ds,price,offer,need,dp);
        int offer_take=1e9;
        vector<int> copyDS=ds;
        for(int i=0; i<need.size(); i++){
            if(copyDS[i]+offer[ind][i]<=need[i]){
                copyDS[i]+=offer[ind][i];
            }else{
                return dp[ind][ds]=min(offer_notTake,offer_take);
            }
        }
        offer_take=offer[ind][price.size()]+ex(ind,copyDS,price,offer,need,dp);
        return dp[ind][ds]=min(offer_notTake,offer_take); 
    }
public:
    int shoppingOffers(vector<int>& price, vector<vector<int>>& offer, vector<int>& need) {
        map<int,map<vector<int>,int>> dp;
        vector<int> ds(need.size(),0);
        return ex(0,ds,price,offer,need,dp);
    }
};

3.2 Shopping Offers Java

class Solution {
    int min = Integer.MAX_VALUE;
    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        solve(0, price, special, needs, 0);
        return min;
    }
    public void solve(int idx, List<Integer> price, List<List<Integer>> special, List<Integer> needs, int bought) {
        if (isFulfilled(needs)) {
            min = Math.min(min, bought);
            return;
        }
        if (idx >= special.size()) {
            int total = bought;
            for (int i = 0; i < needs.size(); i++) {
                total += needs.get(i) * price.get(i);
            }
            min = Math.min(min, total);
            return;
        }
        solve(idx + 1, price, special, needs, bought);
        if (canBuy(needs, special.get(idx))) {
            List<Integer> newNeeds = buyProduct(needs, special.get(idx));
            solve(idx, price, special, newNeeds, bought + special.get(idx).get(needs.size()));
        }
    }
    public boolean isFulfilled(List<Integer> needs) {
        for (int need : needs) {
            if (need != 0) {
                return false;
            }
        }
        return true;
    }
    public boolean canBuy(List<Integer> needs, List<Integer> offer) {
        for (int i = 0; i < needs.size(); i++) {
            if (needs.get(i) < offer.get(i)) {
                return false;
            }
        }
        return true;
    }
    public List<Integer> buyProduct(List<Integer> needs, List<Integer> offer) {
        List<Integer> newNeeds = new ArrayList<>(needs);
        for (int i = 0; i < needs.size(); i++) {
            newNeeds.set(i, needs.get(i) - offer.get(i));
        }
        return newNeeds;
    }
}

3.3 Shopping Offers JavaScript

var shoppingOffers = function(price, special, needs) {
  let betterSpecials = special.filter((s) => 
      !special.some(s2 => s.at(-1) > s2.at(-1) && s.slice(0, -1).every((y, j) => y === s2[j]))
  )
    function check(price, special, needs){
    let offer = needs.reduce((sum, n, i) => sum + n * price[i], 0);
    for(const s of special){
    if(s.some((x, i) => x > needs[i])) continue;
    offer = Math.min(offer, s.at(-1) + check(price, special, needs.map((n, i) => n - s[i])));
        }
        return offer;
    }
    return check(price, betterSpecials, needs);
};

3.4 Shopping Offers Python

class Solution(object):
    def shoppingOffers(self, price, special, needs):
        n = len(price)
        def dfs(needs):
            ans = sum([i*j for i, j in zip(price, needs)]) 
            cur = sys.maxsize
            for s in special:
                new_needs, ok = [], True
                for i in range(n):
                    need, give = needs[i], s[i]
                    if need < give:
                        ok = False
                        break
                    new_needs.append(need-give)    
                if ok: cur = min(cur, dfs(tuple(new_needs)) + s[-1])
            return min(ans, cur)
        return dfs(tuple(needs))

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(m * (max_need)^n)O(m * (max_need)^n)
JavaO(m * (max_need)^n)O(m)
JavaScriptO(m * (max_need)^n)O(m)
PythonO(m * (max_need)^n)O((max_need)^n)
  • Memoization: The C++ and Python implementations use memoization to optimize redundant calculations, making them more efficient than Java and JavaScript implementations.
  • Recursive Depth: The recursion depth is proportional to the number of offers (m), which impacts the space complexity.
  • Knapsack-Like Problem: The problem is a variation of the 0/1 Knapsack problem, where the goal is to minimize cost instead of maximizing value.
Scroll to Top