Data Structures & AlgorithmsHardGATE CS · TCS NQT

Two DP loops count ways to pay 5 using coins 1 and 2 (the order of coins in the sum is ignored in the first version).

Two DP loops count ways to pay 5 using coins 1 and 2 (the order of coins in the sum is ignored in the first version).
coins = [1, 2]
amt = 5
d = [1] + [0] * amt
for c in coins:
    for v in range(c, amt + 1):
        d[v] += d[v - c]
print(d[amt])
What is printed?
  1. A. 8
  2. B. 0
  3. C. 4
  4. D. 3

Correct answer: D. 3

With the outer loop over coins, each coin type is handled once, so the count is unordered (combinations). Swapping the loops, as in the second variant, counts ordered sequences and prints a larger number.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic