Maximum Weight in Two Bags
Problem statement
You have items with weights weights and two bags with capacities w1 and w2. Each item may go into the first bag, into the second bag, or remain unpacked.
An item cannot be split or used in both bags. Neither bag may exceed its capacity. Return the greatest combined weight of the packed items.
Function
maxWeight(weights: int[], w1: int, w2: int) → intExamples
Example 1
weights = [1,4,3,2]w1 = 5w2 = 4return = 9Put weights 3 and 2 in the first bag and weight 4 in the second.
Example 2
weights = [3,6,4,8]w1 = 9w2 = 7return = 15Pack 8 in the first bag and 3 + 4 in the second.
Example 3
weights = [5,7]w1 = 2w2 = 3return = 0Neither item fits in either bag.
Constraints
1 <= weights.length <= 100.1 <= weights[i] <= 100.1 <= w1, w2 <= 300.