Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
Why does the greedy method (best value-per-weight first) solve the fractional knapsack problem but not the 0/1 knapsack problem?
- A. Because sorting by ratio takes too long for 0/1 knapsack
- B. Because fractional knapsack has fewer items
- C. Because 0/1 knapsack has negative weights
- D. Because in 0/1 knapsack an item cannot be split, so leftover capacity may be wasted
Correct answer: D. Because in 0/1 knapsack an item cannot be split, so leftover capacity may be wasted
With fractions the last item can always be cut to fill the bag exactly. With whole items only, taking the best-ratio item can leave unusable space, so 0/1 knapsack needs dynamic programming.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- How many edges does a complete undirected simple graph on 10 vertices have?
- What is the time to search for a word of length L in a trie that holds n words?
- An undirected graph has 12 vertices and the sum of the degrees of all vertices is 40. How many edges does it have?
- The preorder traversal of a BST is 8, 5, 1, 7, 10, 12. What is its postorder traversal?
- A binary tree has inorder 4 8 2 5 1 6 3 7 and preorder 1 2 4 8 5 3 6 7. What is its postorder?
- 10, 4, 7, 1, 3 are inserted in that order into an empty binary min-heap (array form, sift-up after each insert). What is the array at the…