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?- A. 8
- B. 0
- C. 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A monotonic deque computes the minimum of each window of size 3. python from collections import deque a = [4, 2, 12, 11, -5, 7] k = 3 dq =…
- A DP counts the minimum number of coins to pay exactly 11 with coins [2, 5], returning −1 if impossible. python INF = float('inf') coins =…
- A binary search finds the largest x with xx <= 50 using the bounds 0 and 50. python lo, hi = 0, 50 while lo < hi: mid = (lo + hi + 1) // 2…
- A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum. python a = [3, -1, 4, -6…
- A problem asks for the minimum number of refuelling stops on a road, where the car has a fuel capacity and each station offers some fuel…
- For the problem 'choose the largest set of non-overlapping intervals', which greedy rule is correct?