|
| 1 | +# [Problem 3074: Apple Redistribution into Boxes](https://leetcode.com/problems/apple-redistribution-into-boxes/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +We have n packs each with some number of apples, but apples from a single pack can be split across multiple boxes. That means we don't need to worry about pack-level placement constraints — only the total number of apples matters. So we just need enough total box capacity to hold all apples. |
| 5 | + |
| 6 | +Given m boxes with capacities, we want the minimum number of boxes whose capacities sum to at least the total apples. That suggests sorting boxes by capacity descending and taking the largest boxes until their sum >= total apples. That should give the minimum number of boxes because using any smaller box instead of a chosen larger one cannot reduce the count. |
| 7 | + |
| 8 | +Edge cases: total apples may be zero (not in constraints since apple[i] >= 1), or one big box already enough. Problem statement guarantees it's possible (sum(capacity) >= sum(apple)). |
| 9 | + |
| 10 | +## Refining the problem, round 2 thoughts |
| 11 | +No need for complex DP or knapsack because packs are splittable. The greedy choice — pick largest boxes first — is optimal. Proof sketch: if a solution uses k boxes, replacing any used box with a larger unused box only increases capacity; to minimize k we should always pick the largest available capacities. Time complexity driven by sorting capacities: O(m log m). Space complexity O(1) extra (aside from input and sorting). |
| 12 | + |
| 13 | +We should just: |
| 14 | +- compute total_apples = sum(apple) |
| 15 | +- sort capacity descending |
| 16 | +- accumulate capacities until accumulated >= total_apples |
| 17 | +- return count used |
| 18 | + |
| 19 | +Edge cases to consider: |
| 20 | +- Already the largest box suffices. |
| 21 | +- Need all boxes. |
| 22 | +- Small m,n up to 50 so any reasonable approach is fine. |
| 23 | + |
| 24 | +## Attempted solution(s) |
| 25 | +```python |
| 26 | +from typing import List |
| 27 | + |
| 28 | +class Solution: |
| 29 | + def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int: |
| 30 | + total_apples = sum(apple) |
| 31 | + # Sort capacities descending |
| 32 | + capacity.sort(reverse=True) |
| 33 | + acc = 0 |
| 34 | + for i, c in enumerate(capacity): |
| 35 | + acc += c |
| 36 | + if acc >= total_apples: |
| 37 | + return i + 1 |
| 38 | + # Problem guarantees it's possible, but return all boxes as fallback |
| 39 | + return len(capacity) |
| 40 | +``` |
| 41 | +- Notes: |
| 42 | + - Approach: sort capacities in descending order and take the largest boxes until their sum is >= total apples. |
| 43 | + - Time complexity: O(m log m + n) where m = len(capacity), n = len(apple). Sorting dominates: O(m log m). |
| 44 | + - Space complexity: O(1) extra (in-place sort), or O(m) if counting the sort's auxiliary memory. |
0 commit comments