From f7a31a2786674384e76054053b06792f7e557f1b Mon Sep 17 00:00:00 2001 From: Openset Date: Thu, 24 Jan 2019 14:14:57 +0800 Subject: [PATCH] Add: Min Cost Climbing Stairs --- .../min_cost_climbing_stairs.go | 16 ++++++++++++ .../min_cost_climbing_stairs_test.go | 26 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/problems/min-cost-climbing-stairs/min_cost_climbing_stairs.go b/problems/min-cost-climbing-stairs/min_cost_climbing_stairs.go index 8364af07e..51d177876 100644 --- a/problems/min-cost-climbing-stairs/min_cost_climbing_stairs.go +++ b/problems/min-cost-climbing-stairs/min_cost_climbing_stairs.go @@ -1 +1,17 @@ package min_cost_climbing_stairs + +func minCostClimbingStairs(cost []int) int { + f1, f2, l := 0, 0, len(cost)-1 + for i := l; i >= 0; i-- { + f0 := f1 + if f2 < f1 { + f0 = f2 + } + f0 += cost[i] + f1, f2 = f0, f1 + } + if f1 <= f2 { + return f1 + } + return f2 +} diff --git a/problems/min-cost-climbing-stairs/min_cost_climbing_stairs_test.go b/problems/min-cost-climbing-stairs/min_cost_climbing_stairs_test.go index 8364af07e..877175e13 100644 --- a/problems/min-cost-climbing-stairs/min_cost_climbing_stairs_test.go +++ b/problems/min-cost-climbing-stairs/min_cost_climbing_stairs_test.go @@ -1 +1,27 @@ package min_cost_climbing_stairs + +import "testing" + +type caseType struct { + input []int + expected int +} + +func TestMinCostClimbingStairs(t *testing.T) { + tests := [...]caseType{ + { + input: []int{10, 15, 20}, + expected: 15, + }, + { + input: []int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}, + expected: 6, + }, + } + for _, tc := range tests { + output := minCostClimbingStairs(tc.input) + if output != tc.expected { + t.Fatalf("input: %v, output: %v, expected: %v", tc.input, output, tc.expected) + } + } +}