Min Cost Climbing Stairs, DP Solution

One more problem that cab be solved using DP: https://leetcode.com/problems/min-cost-climbing-stairs/description/

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].
Same hints as seen before: looking for min/max, a "cost" function used as the weight, combinatorial is intractable.
Solution is by construction, rather than by induction. Have a DP array which will hold the best solution up to staircase "i". Then build it from 0,1,...,N. At the end, the solution will be either the last element in DP, or the last minus one, whichever is the smallest. Code is below, cheers, Marcelo.


public class Solution
{
 public int MinCostClimbingStairs(int[] cost)
 {
  if (cost == null) return 0;

  int[] dp = new int[cost.Length];

  //Base
  dp[0] = cost[0];
  dp[1] = cost[1];

  //Construction
  for (int i = 2; i < cost.Length; i++)
   dp[i] = cost[i] + Math.Min(dp[i - 1], dp[i - 2]);

  return Math.Min(dp[dp.Length - 1], dp[dp.Length - 2]);
 }
}

Comments

  1. So many memories today - I was asked this problem on my very first Google screen interview. My solution at the time was very similar and used unnecessary linear amount of extra memory, even though all we need is 2 previous costs. The solution with O(1) memory usage is:

    class Solution {
    public:
    int minCostClimbingStairs(const vector& cost) {
    int n_2 = cost.front();
    int n_1 = cost[1];
    for (int i = 2; i < cost.size(); ++i) {
    int new_cost = cost[i] + min(n_2, n_1);
    n_2 = n_1;
    n_1 = new_cost;
    }
    return min(n_2, n_1);
    }
    };

    Cheers,
    Taras

    ReplyDelete

Post a Comment

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

Claude vs ChatGPT: A Coder's Perspective on LLM Performance

ProjectEuler Problem 719 (some hints, but no spoilers)