Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order.
Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order.
def ways(coins, amt):
dp = [1] + [0] * amt
for a in range(1, amt + 1):
for c in coins:
if c <= a: dp[a] += dp[a - c]
return dp[amt]
print(ways([1, 2, 5], 5))What is printed?- A. 4
- B. 8
- C. 5
- D. 9
Correct answer: D. 9
With the amount loop outside, every ORDER of coins is counted separately (1+2+2, 2+1+2, … are different), so it counts compositions: 1, 1, 2, 3, 5, 9. Putting the coin loop outside counts combinations and would give 4.
More Coding Interview Problems questions
- Problem: Find the length of the longest palindromic subsequence of s and the minimum number of insertions that make s a palindrome. python…
- Problem: Matrices A1..A6 have dimensions given by d (Ai is d[i−1] × d[i]). Find the minimum number of scalar multiplications to compute…
- Problem: With e identical eggs, find the minimum number of drops that always identifies the critical floor of an f-floor building. The…
- Problem: Count the ways to place n non-attacking queens on an n × n board. python def queens(n): cols, d1, d2 = set(), set(), set() def…
- Problem: Count the DISTINCT subsets (as multisets) of a list that contains duplicates, using backtracking that skips equal siblings…
- Problem: In an array every value appears twice except two values that appear once. Find those two in O(n) time and O(1) space. python def…