1820. Heavy Knapsack
A courier can load some of n parcels into a van. Parcel i weighs weights[i] and is worth values[i], each parcel can be taken at most once, and the total weight must not exceed capacity. Return the largest total value of any valid load as a long; the empty load is allowed and is worth 0.
The weights are far too large for a table indexed by weight, so split the parcels into two halves, enumerate every (weight, value) pair of each half, sort the second half by weight with a running maximum of value, and for each pair of the first half binary search the best partner that still fits in the remaining capacity. Time about O(2^(n/2) * n), space O(2^(n/2)).
Example 1
- Input:
- weights = [2,3,4], values = [6,10,12], capacity = 5
- Output:
- 16
- Explanation:
Taking the parcels of weight 2 and 3 (total 5) is worth 6 + 10 = 16, the best that fits.
Example 2
- Input:
- weights = [5], values = [7], capacity = 4
- Output:
- 0
- Explanation:
The only parcel weighs 5 but the capacity is 4, so nothing fits.
Example 3
- Input:
- weights = [4], values = [9], capacity = 4
- Output:
- 9
- Explanation:
The single parcel fits exactly and is worth 9.
Constraints
1 ≤ n ≤ 36 (n = weights.length = values.length)
1 ≤ weights[i], values[i] ≤ 1012
1 ≤ capacity ≤ 1014
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 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(2^(n/2) * n)
- Space
- O(2^(n/2))