← Questions
Most packages of at most two items with equal total cost
0
I was asked this
No reports yet. Sign in to say where you were asked it.
You have items with costs item_costs. Make as many packages as you can, where each package holds one or two items, every package has the same total cost, and no item is used twice. You choose the common total. Return the largest number of packages.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
max_packages(item_costs: list[int]) -> int—0for an empty list.
Example
[1, 2, 3, 4] -> 2 # total 5: (1,4) and (2,3)
[2, 2, 2, 2] -> 4 # total 2: four single items beat two pairs at 4
[3, 1, 4, 2, 5, 5] -> 4 # total 5: (5), (5), (1,4), (3,2)
[6, 1, 5, 3, 3, 6, 2] -> 4 # total 6: (6), (6), (1,5), (3,3)
Constraints
-
0 <= len(item_costs) <= 10^4,0 <= item_costs[i] <= 10^9.
Clarifying questions
- May a package hold a single item, or must it hold exactly two?
- Can costs be zero, and does a zero-cost item count as a package on its own?
- Do I return the count only, or the packages too?
What a strong answer covers
- The common total must be some item's cost or the sum of two items' costs, so those are the only candidates:
O(n^2)of them in the worst case, far fewer distinct ones when values repeat. - For a fixed total
S, using every item that costsSas its own package is never worse than pairing it; the rest pair valueawithS - a,min(count[a], count[S - a])times, andcount[a] // 2whena == S - a. - Doing it in one sweep instead of per candidate: over every pair of distinct positive values
a < b, addmin(count[a], count[b])tototal[a + b], andcount[a] // 2tototal[2a]; then add the singlescount[S]to each total. Zeros never go into pairs, since an item alone is as good as that item plus a zero. That isO(D^2)forDdistinct values, with a frequency map. - Tests: an empty list, all equal costs, a single item, zeros.
Follow-ups
- Packages must hold exactly two items.
- Packages may hold up to three items.
- Return the packages themselves.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
