FastPrepMaximum Weight in Two Bags

Maximum Weight in Two Bags

Apple logoApple● MediumFULLTIMEOA
Learn

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) → int

Examples

Example 1

weights = [1,4,3,2]w1 = 5w2 = 4return = 9

Put weights 3 and 2 in the first bag and weight 4 in the second.

Example 2

weights = [3,6,4,8]w1 = 9w2 = 7return = 15

Pack 8 in the first bag and 3 + 4 in the second.

Example 3

weights = [5,7]w1 = 2w2 = 3return = 0

Neither item fits in either bag.

Constraints

  • 1 <= weights.length <= 100.
  • 1 <= weights[i] <= 100.
  • 1 <= w1, w2 <= 300.

More Apple problems

See Apple hiring insights
public int maxWeight(int[] weights, int w1, int w2) {
    // Write your solution here.
}
weights[1,4,3,2]
w15
w24
expected9
Checking account…