Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE
Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or 1, ending beyond the last stair.
Problem: Find the minimum cost to climb stairs where cost[i] is paid on stepping on stair i, moving 1 or 2 stairs, starting at stair 0 or 1, ending beyond the last stair.
def climb(c):
a = b = 0
for i in range(2, len(c) + 1):
a, b = b, min(b + c[i - 1], a + c[i - 2])
return b
print(climb([10, 15, 20]), climb([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))What is printed?- A. 10 6
- B. 15 5
- C. 25 6
- D. 15 6
Correct answer: D. 15 6
dp[i] = min(dp[i − 1] + cost[i − 1], dp[i − 2] + cost[i − 2]) with dp[0] = dp[1] = 0. Start on stair 1 (15) and jump past the top: 15. In the long list, step only on the 1s: six of them. O(n), O(1).
More Coding Interview Problems questions
- Problem: Count the distinct BST shapes that store keys 1..n. python def shapes(n): dp = [1] + [0] n for k in range(1, n + 1): dp[k] =…
- Problem: Count the number of ways to tile a 2 × n board with 2 × 1 dominoes, modulo 10⁹ + 7. cpp const long long MOD = 1e9 + 7; long long…
- Problem: Find the minimum number of perfect squares that sum to n. python def squares(n): dp = [0] + [float('inf')] n for i in range(1, n…
- Problem: Count the number of distinct subsequences of s that equal t. python def distinct(s, t): dp = [1] + [0] len(t) for ch in s: for j…
- Problem: Find the longest increasing path in a matrix (moving up/down/left/right to strictly larger values). python from functools import…
- Problem: Find the cheapest way to cut a stick of length n at given positions; each cut costs the current piece's length. python from…