Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
What is printed? (coin change: number of combinations)
What is printed? (coin change: number of combinations)
def ways(coins, amt):
dp = [1] + [0] * amt
for c in coins:
for a in range(c, amt + 1): dp[a] += dp[a - c]
return dp[amt]
print(ways([2, 5, 3, 6], 10), ways([1, 2, 3], 4))- A. 6 4
- B. 5 4
- C. 5 7
- D. 4 4
Correct answer: B. 5 4
Coins in the outer loop count each multiset once. 10 from {2, 3, 5, 6}: 2+2+2+2+2, 2+2+3+3, 2+2+6, 2+3+5, 5+5 = 5. 4 from {1, 2, 3}: 1+1+1+1, 1+1+2, 2+2, 1+3 = 4. With the loops swapped you would count ordered sequences (7 for the second). O(amount × coins).
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
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…
- What is printed? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…
- What is printed? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…
- What is printed? (0/1 knapsack with item reconstruction) python w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4 dp = [[0] (W + 1) for in…
- What is printed? (number of BSTs vs number of binary heaps on keys 1..4) python from math import comb from functools import lrucache…
- What is printed? (diameter of an unweighted tree with two BFS passes) python from collections import deque edges = [(1, 2), (1, 3), (2…