šŸŽ’
Technical Interview Study Guide
  • šŸ•Welcome!
  • šŸ„Getting Started
    • Study Plan
    • Optimizing Revision
    • Summer 2024 Timeline
    • FAQs
  • 🄨Algorithms
    • Binary Search
    • Sorting
    • Recursion
    • Graph
    • Quick Select
    • Intervals
    • Binary
    • Geometry
    • Dynamic Programming
  • šŸ„žData Structures
    • Arrays
      • Matrices
    • Strings
    • Linked Lists
      • Doubly Linked Lists
    • Hash Tables
    • Graphs
      • Trees
        • Binary Search Trees
        • Heaps
        • Tries
        • Segment Trees
    • Stacks
    • Queues
      • Double Ended Queues
    • Union-Find Disjoint Set (UFDS)
  • šŸ”Problems Guide
    • Dynamic Programming Roadmap
      • Warmup
        • Climbing Stairs
        • Nth Tribonacci Number
        • Perfect Squares
      • Linear Sequence
        • Min Cost to Climb Stairs
        • Minimum Time to Make Rope Colorful
        • House Robber
        • Decode Ways
        • Minimum Cost for Tickets
        • Solving Questions with Brainpower
  • šŸ£Other Technical Topics
    • General Problem Solving
    • Runtime Predictions
    • System Design
      • SQL
      • Accessing APIs
    • Operating Systems
  • šŸæNon-technical Topics
    • Behavioral Interviews
    • Resumes
Powered by GitBook
On this page
  • Observations
  • Recurrence relation
  • Bottom-up
  1. Problems Guide
  2. Dynamic Programming Roadmap
  3. Linear Sequence

Min Cost to Climb Stairs

Observations

  • On each step n, we must incur the cost since we have to decide whether or not to move one or two steps up

  • To reach step n, you must move from step n - 1 or step n - 2

  • To minimize the cost to reach step n, we need to minimize the cost it takes to reach it

Recurrence relation

dp(n)={cost(0),n=0cost(1),n=1min⁔(dp(nāˆ’1),dp(nāˆ’2))+cost(n)dp(n) = \begin{cases} cost(0), n = 0\\ cost(1), n = 1\\ \min(dp(n-1),dp(n-2)) + cost(n) \end{cases}dp(n)=āŽ©āŽØāŽ§ā€‹cost(0),n=0cost(1),n=1min(dp(nāˆ’1),dp(nāˆ’2))+cost(n)​

We can define dp(n)dp(n)dp(n) as the minimum cost it takes to climb from step nnn. If we start at the first step, the cost is cost(0)cost(0)cost(0) and if we start at the second step, the cost is cost(1)cost(1)cost(1). Otherwise, for every step nnn, the cost to climb from it is the cost it took to reach it with the cost of leaving the step.

Bottom-up

The nnn state caching optimization can be applied here again, given that each state depends only on the previous 2 states.

def climb_stairs(costs):
    s1, s2 = costs[0], costs[1]
    for i in range(2, len(costs)):
        s1, s2 = s2, min(s1, s2) + costs[i]
    return min(s1, s2)
PreviousLinear SequenceNextMinimum Time to Make Rope Colorful

Last updated 1 year ago

šŸ”