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?
  1. A. 10 6
  2. B. 15 5
  3. C. 25 6
  4. 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

Exams that ask this topic