Skip to content

Knapsack Light

You found two items in a treasure chest! The first item weighs weight1 and is worth value1, and the second item weighs weight2 and is worth value2. What is the total maximum value of the items you can take with you, assuming that your max weight capacity is maxW and you can't come back for the items later?

Note

There are only two items and you can't bring more than one item of each type, i.e. you can't take two first items or two second items.

Example

  • For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 8, the output should be

    knapsack_light(value1, weight1, value2, weight2, maxW) = 10

    You can only carry the first item.

  • For value1 = 10, weight1 = 5, value2 = 6, weight2 = 4, and maxW = 9, the output should be

    knapsack_light(value1, weight1, value2, weight2, maxW) = 16

    You're strong enough to take both of the items with you.

  • For value1 = 5, weight1 = 3, value2 = 7, weight2 = 4, and maxW = 6, the output should be

    knapsack_light(value1, weight1, value2, weight2, maxW) = 7

    You can't take both items, but you can take any of them.

Solution

py
def knapsack_light(value_1, weight_1, value_2, weight_2, max_weight):
    if weight_1 + weight_2 <= max_weight:
        return value_1 + value_2
    elif weight_1 <= max_weight and weight_2 <= max_weight:
        return max(value_1, value_2)
    elif weight_1 <= max_weight:
        return value_1
    elif weight_2 <= max_weight:
        return value_2
    else:
        return 0


print(knapsack_light(10, 5, 6, 4, 8))
js
function knapsackLight(value1, weight1, value2, weight2, maxW) {
  if (weight1 + weight2 <= maxW) {
    return value1 + value2;
  } else if (weight1 <= maxW && weight2 <= maxW) {
    return Math.max(value1, value2);
  } else if (weight1 <= maxW) {
    return value1;
  } else if (weight2 <= maxW) {
    return value2;
  } else {
    return 0;
  }
}

console.log(knapsackLight(10, 5, 6, 4, 8));

my thoughts are neither my employer's nor my wife's