Data Structures and Algorithms

A knapsack with capacity 8 is filled with items chosen from four items with (weight, value) of (2, 3), (3, 4), (4, 5) and (5, 6). There is only one of each item and items cannot be split. What is the maximum total value with a total weight of 8 or less?

  1. A7
  2. B9
  3. C10
Show answer and explanation

Answer: C. 10

Choosing the items of weight 3 and 5 gives weight 8 and value 4 + 6 = 10, which is the maximum. Weights 2 and 5 (value 9) or 3 and 4 (value 9) also fit but fall short of 10, and any three items weigh at least 2 + 3 + 4 = 9, over the capacity. A greedy algorithm that packs items in order of value per unit weight takes the items of weight 2 and 3 (value 7), and then no item fits in the remaining capacity of 3, so it stops at 7. Dynamic programming updates a table of the best value achievable within each capacity c item by item, and finds the optimum in O(nW) for n items and capacity W.

  • A. This is the result of a greedy algorithm that packs by value per unit weight, which is not optimal.
  • B. This is the value of weights 2 and 5, or 3 and 4, which is not the maximum.
  • C. Correct. The items of weight 3 and 5 use the capacity of 8 exactly and give a value of 10.
Practice this topic Back to topic

Related calculators

Books on Data Structures and Algorithms Ad

As an Amazon Associate I earn from qualifying purchases.

More Data Structures and Algorithms questions

  1. Which is a characteristic of the Boyer-Moore algorithm for finding a pattern in a string?
  2. A dynamic array, when an element is added while it is full, allocates a new area with twice the capacity and copies all elements into it. If 1,000 elements are added one at a time to an empty array of capacity 1, how many element copies are made in total?
  3. For a hash table with many elements kept at a load factor of about 0.5, which is the most appropriate reason that open addressing with linear probing tends to be faster than chaining (linking elements with linked lists)?
  4. Sorting methods with a fixed sequence of compare-exchange steps (sorting networks), such as bitonic sort, are sometimes used for sorting on parallel hardware such as GPUs. Why?
  5. For an array of n elements, what is the time complexity of comparing every pair of distinct elements exactly once (a double loop that compares element i with every element after it, advancing i one step at a time)?