1528. Subsets Within Budget

Easy1.5 points estimatedBitmaskEnumerationArray

A shopper looks at a small shelf of gadgets whose prices are listed in the array prices, and has a spending limit of budget. A basket is any subset of the gadgets, chosen by position, so two gadgets with the same price at different positions count as different choices. The empty basket is allowed and costs nothing.

Return the number of baskets whose total price is at most budget. Since there are at most 15 gadgets, you can enumerate every bitmask from 0 to 2^n - 1, where bit i tells whether gadget i is in the basket, and add up the chosen prices. This takes O(2^n * n) time and O(1) extra space. The total cost of a basket can exceed 32 bits only in theory, so accumulate carefully.

Example 1

Input:
prices = [2,3,5], budget = 6
Output:
5
Explanation:

The affordable baskets are {}, {2}, {3}, {5}, {2,3}, which is 5.

Example 2

Input:
prices = [4,4], budget = 3
Output:
1
Explanation:

Only the empty basket costs at most 3, so the answer is 1.

Constraints

1 ≤ n ≤ 15; 1 ≤ prices[i] ≤ 106; 0 ≤ budget ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(2^n * n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…