Skip to main content

Maximum Number of Items From Sale II - Solution & Explanation

Practice this problem

Problem Statement

You are given a 2D integer array items, where items[i] = [factori, pricei] represents the ith item. You are also given an integer budget.

There are unlimited copies of each item available for purchase. You may buy any number of copies of any items such that the total cost of the purchased copies is at most budget.

After buying items, you may receive free copies according to the following rules:

  • Each purchased copy of item i can give you at most one free copy of another item j.
  • The free item must satisfy i != j and factori divides factorj.
  • For each ordered pair (i, j), you can receive a free copy of item j from purchases of item i at most once, regardless of how many copies of item i you buy.
  • The same item j can be received multiple times for free if it is received from purchases of different item types.

Return the maximum total number of item copies you can obtain, including both purchased copies and free copies, while spending at most budget on purchased items.

 

Example 1:

Input: items = [[1,6],[2,4],[3,5]], budget = 19

Output: 5

Explanation:

  • You can buy 2 copies of item 0 and 1 copy of item 1 for a total cost of 2 * 6 + 4 = 16, which is not greater than budget = 19.
  • One purchased copy of item 0 gives 1 free copy of item 1, because factor0 = 1 divides factor1 = 2.
  • The other purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 1 divides factor2 = 3.
  • You leave with 3 purchased copies and 2 free copies, for a total of 5 item copies.

Example 2:

Input: items = [[2,8],[1,10],[6,6],[4,12],[5,20],[5,17]], budget = 35

Output: 7

Explanation:

  • You can buy 2 copies of item 0, 1 copy of item 1, and 1 copy of item 2 for a total cost of 2 * 8 + 10 + 6 = 32, which is not greater than budget = 35.
  • One purchased copy of item 0 gives 1 free copy of item 2, because factor0 = 2 divides factor2 = 6.
  • The other purchased copy of item 0 gives 1 free copy of item 3, because factor0 = 2 divides factor3 = 4.
  • The purchased copy of item 1 gives 1 free copy of item 2, because factor1 = 1 divides factor2 = 6.
  • Buying item 2 gives no free copy, because factor2 = 6 does not divide the factor of any other item.
  • You leave with 4 purchased copies and 3 free copies, for a total of 7 item copies.

 

Constraints:

  • 1 <= items.length <= 105
  • items[i] = [factori, pricei]
  • 1 <= factori <= items.length
  • 1 <= pricei <= 109
  • 1 <= budget <= 109

Approach Overview

Problem Overview: You are given item prices, a limited number of coins, and a fixed number of discount coupons. Each coupon can reduce the price of one item (for example, half price). The goal is to maximize how many items you can buy without exceeding the coin budget.

Approach 1: Brute Force Subset Search (Exponential Time)

Enumerate every subset of items and simulate applying coupons in the most beneficial way for that subset. For each chosen group, assign coupons to the most expensive items and check whether the total cost stays within the coin limit. This guarantees the optimal result but requires checking 2^n subsets, giving O(2^n * n log n) time and O(n) space. It quickly becomes infeasible even for moderate input sizes.

Approach 2: Greedy with Sorting (O(n log n) time, O(1) space)

Sort items by price and buy the cheapest items first. This greedy idea works well when coupons are not involved because minimizing cost lets you purchase more items. After sorting, iterate through the prices and subtract from the coin budget until the budget runs out. While simple, this strategy fails when coupons should be applied to expensive items later in the purchase sequence.

Approach 3: Greedy + Max Heap for Coupon Optimization (O(n log n) time, O(n) space)

Sort items by price and iterate through them while simulating purchases. Maintain a running total cost and a max heap storing the prices of items bought so far. When coupons are available, you can retroactively apply a coupon to the most expensive purchased item to reduce the total cost. This works because applying discounts to larger prices yields the biggest savings. Each time the cost exceeds the coin budget, use a coupon on the highest price from the heap (if any remain) and adjust the total. The heap ensures the optimal coupon placement with O(log n) updates.

This pattern appears in problems combining greedy decision making with dynamic re‑evaluation using a priority queue. Sorting establishes purchase order, while the heap allows you to reassign discounts to maximize savings.

Recommended for interviews: The greedy + heap approach is the expected solution. Brute force demonstrates understanding but is not scalable. Interviewers typically want to see the insight that coupons should always be applied to the most expensive purchased item, implemented efficiently using a priority queue.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Subset SearchO(2^n * n log n)O(n)Only for conceptual understanding or very small inputs
Greedy After SortingO(n log n)O(1)Works when coupons or dynamic discounts are not involved
Greedy + Max HeapO(n log n)O(n)General case with coupons or adjustable discounts

Video Solution

Maximum Number of Items From Sale II | Leetcode 3947 • Techdose • 735 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Maximum Number of Items From Sale II easy or hard?
The problem is considered Medium difficulty. The main challenge is recognizing that coupons should be applied to the highest-priced purchased item and implementing this efficiently using a heap after sorting.
Maximum Number of Items From Sale II Python/Java solution
Typical implementations sort the price array, maintain a running total cost, and store purchased prices in a priority queue. Python uses heapq with negative values to simulate a max heap, while Java uses PriorityQueue with a reverse comparator.
How to solve Maximum Number of Items From Sale II in O(n log n)?
Sort items by price, then iterate through them while tracking total cost. Push each purchased price into a max heap. If the total cost exceeds the available coins, apply a coupon to the largest price in the heap to reduce the cost. Heap operations keep the algorithm within O(n log n).
What is the best approach for Maximum Number of Items From Sale II?
The most efficient approach uses a greedy strategy combined with a max heap (priority queue). Items are processed in increasing price order while maintaining purchased prices in a heap. Coupons are applied to the most expensive purchased item to reduce total cost. This approach runs in O(n log n) time and O(n) space.
Is Maximum Number of Items From Sale II asked at Google/Amazon/Meta?
Problems combining greedy strategies with priority queues frequently appear in interviews at companies like Amazon and Google. Variants that require maximizing purchases under a budget with discounts or coupons are common because they test both greedy reasoning and heap usage.
What data structure is used in Maximum Number of Items From Sale II?
The key data structure is a max heap (priority queue). It allows efficient retrieval of the most expensive purchased item so a coupon can be applied where it provides the greatest savings. Sorting and greedy iteration are also core components of the solution.
What is the time complexity of Maximum Number of Items From Sale II?
The optimal solution runs in O(n log n) time due to sorting the item prices and performing heap operations. Each item may be inserted or removed from the heap once. Space complexity is O(n) for the priority queue storing purchased item prices.

Ready to solve this problem?

Practice Maximum Number of Items From Sale II with our built-in code editor and test cases.

Practice on FleetCode