Approach
Sorting and greedy selection
For Maximum Number of Items from Sale II, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 40 lines of Python from the credited upstream file maximum-number-of-items-from-sale-ii.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4import collections5 6 78class Solution(object):9 def maximumSaleItems(self, items, budget):10 """11 :type items: List[List[int]]12 :type budget: int13 :rtype: int14 """15 NEG_INF = float("-inf")16 cnt = [0]*(max(f for f, _ in items)+1)17 for f, _ in items:18 cnt[f] += 119 total = [0]*len(cnt)20 for i in xrange(1, len(total)):21 if not cnt[i]:22 continue23 for j in xrange(i, len(total), i):24 total[i] += cnt[j]25 min_p = min(p for _, p in items)26 group = collections.defaultdict(int)27 for f, price in items:28 if price >= 2*min_p:29 continue30 group[price] += total[f]-131 result = 032 for p in sorted(group):33 c = min(group[p], budgetp)34 result += 2*c35 budget -= c*p36 if not budget:37 break38 result += budgetmin_p39 return result40