Min Cost Climbing Stairs - Dynamic Programming - Leetcode 746 - Python

Sdílet
Vložit
  • čas přidán 28. 07. 2024
  • 🚀 neetcode.io/ - A better way to prepare for Coding Interviews
    🐦 Twitter: / neetcode1
    🥷 Discord: / discord
    🐮 Support the channel: / neetcode
    ⭐ BLIND-75 PLAYLIST: • Two Sum - Leetcode 1 -...
    💡 CODING SOLUTIONS: • Coding Interview Solut...
    💡 DYNAMIC PROGRAMMING PLAYLIST: • House Robber - Leetco...
    🌲 TREE PLAYLIST: • Invert Binary Tree - D...
    💡 GRAPH PLAYLIST: • Course Schedule - Grap...
    💡 BACKTRACKING PLAYLIST: • Word Search - Backtrac...
    💡 LINKED LIST PLAYLIST: • Reverse Linked List - ...
    💡 BINARY SEARCH PLAYLIST: • Binary Search
    📚 STACK PLAYLIST: • Stack Problems
    Problem Link: neetcode.io/problems/min-cost...
    0:00 - Read the problem
    4:00 - Drawing Brute Force
    6:32 - Drawing Memoization
    10:40 - Drawing Dynamic Programming
    16:02 - Coding DP Solution
    leetcode 746
    This question was identified as a google interview question from here: github.com/xizhengszhang/Leet...
    #coding #interview #python
    Disclosure: Some of the links above may be affiliate links, from which I may earn a small commission.
  • Věda a technologie

Komentáře • 79

  • @NeetCode
    @NeetCode  Před 2 lety +5

    💡 DYNAMIC PROGRAMMING PLAYLIST: czcams.com/video/73r3KWiEvyk/video.html

  • @inf2004
    @inf2004 Před 2 lety +111

    You are the best among leetcode solving youtube channels, others are not even close in quality of explanation... It would be nice if leetcode hire you to write content for "solution" tabs...

    • @NeetCode
      @NeetCode  Před 2 lety +14

      I appreciate the kind words :)

  • @chaitanyavarma2097
    @chaitanyavarma2097 Před 2 lety +43

    this is exactly how we should approach a problem - from the first principles. lots of other youtubers just copy paste a discussion solution without understanding what's happening. great stuff!

  • @resa_uyi
    @resa_uyi Před 2 lety +38

    You are an asset to the programming world. Thank you.

  • @letscode1000
    @letscode1000 Před 2 lety +20

    we can also use top down solution with 3 lines of codes:
    for i in range(2, len(cost)):
    cost[i] += min(cost[i - 1], cost[i - 2])
    return min(cost[-2:])

    • @atithi8
      @atithi8 Před rokem

      This is what I did.

    • @Jaswanth-my8wq
      @Jaswanth-my8wq Před 8 měsíci

      if you're adding a 0 at the end like he did, you can just return cost[-1]. seems more easy to understand this way atleast for me

    • @hwang1607
      @hwang1607 Před 5 měsíci +2

      I think this is a better solution and more closely follows the first climbing stairs question, heres your solution if you cannot change the original array
      class Solution:
      def minCostClimbingStairs(self, cost: List[int]) -> int:
      a = cost[0]
      b = cost[1]
      for i in range(2, len(cost)):
      temp = b
      b = cost[i] + min(a,b)
      a = temp
      return min(a ,b)

    • @vijethkashyap151
      @vijethkashyap151 Před 4 dny

      How's it Top down? It's still bottom up right? Just the direction of iteration has reversed. But answer still depends on subproblem of i -1 and i -2?

  • @servantofthelord8147
    @servantofthelord8147 Před 22 dny +1

    Such a cool problem to learn about dynamic programming right after "Climbing Stairs". Your roadmap is GOATED! I've been grinding the "Neetcode All" and I've been having the time of my life.

  • @alexm1930
    @alexm1930 Před 2 lety +20

    Hey, you probably realize this by now. But you don't really need to append a 0 or start at 15 in the example you showed. You can just start at 10 in that example since the last 2 spots will never change since the end can be reached by either of those spots.

  • @pshr2447
    @pshr2447 Před 2 lety +9

    your channel is like a gift from God ngl

  • @shubhammishra1225
    @shubhammishra1225 Před 2 lety +3

    After explanation without watching coding part I solved this. Nice explanation.

  • @nero9985
    @nero9985 Před 2 lety +8

    Are DP questions really common on interviews? I feel like only Google would ask them, I got asked House Robber on their phone screen.

  • @rock23754
    @rock23754 Před 2 lety

    thank you so much for providing such beautiful solutions!

  • @atg878
    @atg878 Před 5 měsíci

    no one literally takes me through the dp this level except you ,thank you 🤞🤞🤞🤞🤞🤞🤞🤞

  • @gouravkumarshaw5467
    @gouravkumarshaw5467 Před 2 lety +1

    Great Explanation Thanks!!!

  • @TheSimilarBoy
    @TheSimilarBoy Před 2 lety +8

    A more compact implementation of the same algorithm:
    cur = nxt = 0
    for c in cost[::-1]:
    cur, nxt = c + min(cur, nxt), cur
    return min(cur, nxt)

  • @mikhailvas6666
    @mikhailvas6666 Před rokem

    Your videos are my best find on the way to my dream!

  • @aboudithebault8828
    @aboudithebault8828 Před 2 lety +8

    Dude just... thanks. You are Abdul Bari level

  • @hassan7569
    @hassan7569 Před 2 lety +7

    it would be better for the brute force to start at an imaginary -1 index, so that you don't need to go through the decision tree again to get the following index's decision tree.

  • @sushilkhadka8069
    @sushilkhadka8069 Před 2 lety +2

    You are a gift from god. Regretting why didn't I find you before

  • @whonayem01
    @whonayem01 Před 2 lety +1

    Thanks.
    I think we don't need to add 0 at the end since the cost can't be negative.

  • @serena_siyanguo2849
    @serena_siyanguo2849 Před rokem

    thank you for walking through your thought process! only wish you were a java programmer... : )

  • @ilyaantonenko3812
    @ilyaantonenko3812 Před 2 lety +2

    Thanks!

  • @alasdairmacintyre9383
    @alasdairmacintyre9383 Před rokem +5

    FYI, it isn't necessary to start by appending 0 to the list. But you can keep everything else the same and still start with length(list)-3, because the cost of the last 2 items will always be its own value

  • @apriil9822
    @apriil9822 Před 2 lety +1

    NeetCode: yeah, that's the entire code...
    Me: magic!!!

  • @akhma102
    @akhma102 Před rokem

    Simply the Best!

  • @shamsularefinsajib7778
    @shamsularefinsajib7778 Před 9 měsíci +5

    This IS NOT an EASY problem for everyone!! should be marked as MEDIUM

  • @moeinhasani8718
    @moeinhasani8718 Před měsícem

    correct me if I'm wrong but we don't necessarily need to add the 0 because whenever we get to the n-2 index it is always better to make a doble jump rather than one jump. so cost of that index is its own value. so we start from n-3 and go toward the stat and don't need to update the n-2 value.

  • @HalfJoked
    @HalfJoked Před 2 lety +3

    Great explanation! However, modifying the original input can be considered bad practice - what if the interviewer doesn't want that?
    Alternative answer, passes all test cases:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    one = two = 0
    for i in range(2, len(cost) + 1):
    temp = one
    one = min(one + cost[i - 1], two + cost[i - 2])
    two = temp
    return one

    • @chethansaikrishna8401
      @chethansaikrishna8401 Před 7 měsíci

      This is a better incremental understanding if you have learnt in sequence of Bottom Up for => fibonacci -> Climbing Stairs -> Now
      def stairsbu():
      c = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
      n = 10
      i = 2
      cache = [0, 0]
      while(i

  • @anybody413
    @anybody413 Před 2 lety

    U R the BEST!!

  • @The6thProgrammer
    @The6thProgrammer Před 8 měsíci +1

    Nice video, but similar to the "Climbing Stairs" problem, I don't see a benefit from starting at the end of the array, and it makes it more confusing (even more so for this one than climbing stairs). Since you can start at 0 or 1 index, it is easy to simply say the answer to the next index is min(cost[i -1], cost[i - 2]) + cost[i] starting from i = 2. Since when we are at i, we always have to pay the cost of landing at i, whether we take 1 step or 2.

  • @asdfasyakitori8514
    @asdfasyakitori8514 Před 9 měsíci

    Great video

  • @jourdanooi3324
    @jourdanooi3324 Před 2 měsíci

    Tiny optimization but you don't have to start at len(arr)-3 you can start at len(arr)-4 bc the second to last element will never be smaller if it jumps to the last element first before the end of the staircase. It will always stay the same.

  • @darshandani1
    @darshandani1 Před 5 měsíci

    Brilliant !

  • @moqimhaidari7761
    @moqimhaidari7761 Před rokem

    I liked the explanation

  • @Dennis-ym4gk
    @Dennis-ym4gk Před 2 lety

    Hi, I was just wondering why you don't use the solution from house robber to solve this problem?

  • @harshtita3184
    @harshtita3184 Před rokem

    You are one heck of a problem solver and on top of that a great explainer. Cheers friend!

    • @harshtita3184
      @harshtita3184 Před rokem

      C++ code:
      int n=cost.size();
      int dp[n+2];
      dp[n+1]=0;dp[n]=0;
      int jumpCost1,jumpCost2;
      for(int i=n-1;i>=0;i--){
      jumpCost1=cost[i]+dp[i+1];
      jumpCost2=cost[i]+dp[i+2];
      dp[i]=min(jumpCost1,jumpCost2);
      }

      return min(dp[0],dp[1]);

  • @ajaysenger2
    @ajaysenger2 Před měsícem

    Maza aa raha hai dil garden garden ho raha hai ek bar mein 3eno se solve Kar liya

  • @julioarath2621
    @julioarath2621 Před rokem

    for i in range(2,len(cost)):
    cost[i]+=min(cost[i-1],cost[i-2])
    return min(cost[-1],cost[-2])

  • @venkatasundararaman
    @venkatasundararaman Před 3 měsíci

    We can do it similar to the climbing stairs problem as follows
    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    one, two = 0, 0
    for i in range(len(cost)-1, -1, -1):
    cost[i] += min(one, two)
    two = one
    one = cost[i]
    return min(one, two)

  • @shivanishivani8060
    @shivanishivani8060 Před 2 lety

    great content keep doing & make explaination easier

  • @OMPRAKASH-is7fj
    @OMPRAKASH-is7fj Před 9 měsíci

    nice one

  • @JWC7
    @JWC7 Před 19 dny

    craziest part, you dont even need to go reverse order

  • @lunaa9737
    @lunaa9737 Před rokem

    you're the best

  • @howheels
    @howheels Před rokem +1

    I don't like that this solution mutates the original dataset. Also, I felt unsatisfied when you explained a DFS + memoization algorithm, but then coded an iterative solution instead. However, I was able to code my own solution using recursion + cache with your clear explanation, which personally I find more intuitive than iterating in reverse!

    • @ehabahmedyassen
      @ehabahmedyassen Před rokem +2

      +1 I prefer the recursion + memoization version. The Tabulation version here seems a bit complex.

    • @anotheraleks
      @anotheraleks Před rokem +2

      hey! I implemented the recursion + memoization version and it fails time limits on high load test cases. Can you show your version please?

  • @cachestache2485
    @cachestache2485 Před 2 lety

    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    for i in range(2, len(cost)):
    cost[i] += min(cost[i - 1], cost[i - 2])
    return min(cost[-1], cost[-2])

  • @AlancRodriguez
    @AlancRodriguez Před 9 měsíci

    Beautiful

  • @danielsun716
    @danielsun716 Před rokem

    We can make sure the last two min values should be themselves. So there is no need to append another 0
    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    #cost.append(0)
    for i in range(len(cost) - 3, -1, -1):
    cost[i] = min(cost[i] + cost[i + 1], cost[i] + cost[i + 2])
    return min(cost[0], cost[1])

  • @TypicalRussianGuy
    @TypicalRussianGuy Před rokem +1

    It's weird that the problem is called "climbing stairs".
    I mean, what stairs have one step being 100 times more expensive to climb that the previous one?
    Why didn't they call the problem "saving fuel on an airplane" or something.

  • @geekydanish5990
    @geekydanish5990 Před 2 lety +1

    top down + memo
    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    dp = {} #{step:min_cost}
    def helper(n):
    if n == 0:
    return cost[0]
    if n == 1:
    return cost[1]
    if n in dp:
    return dp[n]
    one_step_cost = helper(n-1)+cost[n]
    two_step_cost = helper(n-2)+cost[n]
    min_cost = min(one_step_cost,two_step_cost)
    dp[n] = min_cost
    return min_cost
    return min(helper(len(cost)-1),helper(len(cost)-2))

  • @Lulit999
    @Lulit999 Před rokem +1

    Instead of going from the end to the start we can go from the start to the end (without -1 in range)
    Code:
    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    for x in range(2, len(cost)):
    cost[x] += min(cost[x-1], cost[x-2])

    return min(cost[-2], cost[-1])

  • @sanooosai
    @sanooosai Před 5 měsíci

    great

  • @chaitanyaprasad6924
    @chaitanyaprasad6924 Před rokem

    This is just reverse greedy in a way. !! It not even seems like DP

  • @rabbyhossain6150
    @rabbyhossain6150 Před 6 měsíci

    Recursive solution:
    class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    cache = {}
    def dfs(i):
    if i >= len(cost):
    return 0
    elif i in cache:
    return cache[i]
    cache[i] = min(cost[i] + dfs(i + 1), cost[i] + dfs(i + 2))
    return cache[i]
    dfs(0)
    return min(cache[0], cache[1])

  • @vijayakumareyunni6010
    @vijayakumareyunni6010 Před 7 měsíci

    Easier problem explained in a difficult way.

  • @Khalid-fx9sm
    @Khalid-fx9sm Před rokem

    your brute force solution misses the fact that we can start at either position 0 or position 1, we can run two seperate stack traces from each poisiton and get the min, or we can start jumping from position -1. the cost there is 0, and it can either jump to position 0 or position 1.
    my bruteforce code:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
    minC = 10000000000000
    def jump(n, c, minC):
    if n >= len(cost):
    minC = min(minC, c)
    return minC
    if n > -1:
    c += cost[n]
    return min(jump(n + 1, c, minC), jump(n + 2, c, minC))
    return jump(-1, 0, minC)

  • @ocdvape3771
    @ocdvape3771 Před 4 měsíci

    Is it just me that prefers the recursive solution to this?

  • @samuelwong6352
    @samuelwong6352 Před rokem

    7:58

  • @supremoluminary
    @supremoluminary Před rokem

    You lost me with Python. I mostly followed along up until then.

  • @Karan-gh9ki
    @Karan-gh9ki Před 6 měsíci

    yea you fucked up this explanation

  • @010101dddm
    @010101dddm Před rokem +1

    Quite misleading explanation

  • @pilotwave_
    @pilotwave_ Před 2 lety +1

    would be nice to cut down long explanation, need to say what needs to be said concisely avoiding tiring wordiness.

  • @naveenprasanthsa3749
    @naveenprasanthsa3749 Před 2 lety

    Facebook, whatsapp, Instagram down

    • @pshr2447
      @pshr2447 Před 2 lety

      yooo actually i was wondering what tf was up and why i couldn't dm my mate

    • @NeetCode
      @NeetCode  Před 2 lety +37

      at least leetcode is still up lol..

  • @MeetManga
    @MeetManga Před 2 lety

    I do believe that we dont need the line of "cost.append(0)" , I just removed it , and still works

  • @sneakyblinder982
    @sneakyblinder982 Před měsícem

    Thanks!