From 066a84272c94a9b779aafb86972ce1ddb962b961 Mon Sep 17 00:00:00 2001 From: Shyam-Chen Date: Sat, 26 Oct 2024 22:44:32 +0800 Subject: [PATCH] 243rd Commit --- README.md | 3 ++- .../minCostClimbingStairs.test.ts | 8 ++++++++ .../minCostClimbingStairs.ts | 16 ++++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.test.ts create mode 100644 src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.ts diff --git a/README.md b/README.md index 58e33f5..7bb8d8e 100644 --- a/README.md +++ b/README.md @@ -243,11 +243,12 @@ Ace Coding Interview with 75 Qs | DP - 1D | | | | ------------------------------ | ---------------- | ------ | | 1137. N-th Tribonacci Number | [Solution][1137] | Easy | -| 746. Min Cost Climbing Stairs | Solution | Easy | +| 746. Min Cost Climbing Stairs | [Solution][746] | Easy | | 198. House Robber | Solution | Medium | | 790. Domino and Tromino Tiling | Solution | Medium | [1137]: ./src/page-11/1137.%20N-th%20Tribonacci%20Number/tribonacci.ts +[746]: ./src/page-7/746.%20Min%20Cost%20Climbing%20Stairs/minCostClimbingStairs.ts | DP - Multidimensional | | | | --------------------------------------------------------- | -------- | ------ | diff --git a/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.test.ts b/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.test.ts new file mode 100644 index 0000000..4b8ec4e --- /dev/null +++ b/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.test.ts @@ -0,0 +1,8 @@ +import { minCostClimbingStairs } from './minCostClimbingStairs'; + +describe('746. Min Cost Climbing Stairs', () => { + test('minCostClimbingStairs', () => { + expect(minCostClimbingStairs([10, 15, 20])).toBe(15); + expect(minCostClimbingStairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1])).toBe(6); + }); +}); diff --git a/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.ts b/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.ts new file mode 100644 index 0000000..1286fd7 --- /dev/null +++ b/src/page-7/746. Min Cost Climbing Stairs/minCostClimbingStairs.ts @@ -0,0 +1,16 @@ +type MinCostClimbingStairs = (cost: number[]) => number; + +/** + * Accepted + */ +export const minCostClimbingStairs: MinCostClimbingStairs = (cost) => { + const n = cost.length; + const dp: number[] = new Array(n + 1).fill(0); + + // Populate dp array using the state transition + for (let i = 2; i <= n; i++) { + dp[i] = Math.min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]); + } + + return dp[n]; +};