mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
dynamic-programming(i): add day 2 and rename day 1
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
5d622d4583
commit
c1a688bf2f
4 changed files with 55 additions and 0 deletions
27
study-plan/dynamic-programming/day-02/climbing-stairs.rb
Normal file
27
study-plan/dynamic-programming/day-02/climbing-stairs.rb
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
# @param {Integer} n
|
||||||
|
# @return {Integer}
|
||||||
|
def climb_stairs(n)
|
||||||
|
possible_ways = [0, 1, 2]
|
||||||
|
|
||||||
|
k = 3
|
||||||
|
while possible_ways.size <= n do
|
||||||
|
possible_ways.push(possible_ways[k - 1] + possible_ways[k - 2])
|
||||||
|
k += 1
|
||||||
|
end
|
||||||
|
|
||||||
|
return possible_ways[n]
|
||||||
|
end
|
||||||
|
|
||||||
|
RSpec.describe "climb_stairs" do
|
||||||
|
it "1 is 1" do
|
||||||
|
expect(climb_stairs(1)).to eq(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "2 is 2" do
|
||||||
|
expect(climb_stairs(2)).to eq(2)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "3 is 3" do
|
||||||
|
expect(climb_stairs(3)).to eq(3)
|
||||||
|
end
|
||||||
|
end
|
|
@ -0,0 +1,28 @@
|
||||||
|
# @param {Integer[]} cost
|
||||||
|
# @return {Integer}
|
||||||
|
def min_cost_climbing_stairs(cost)
|
||||||
|
def get(cost, k)
|
||||||
|
if k < 0 || k >= cost.size then
|
||||||
|
return 0
|
||||||
|
end
|
||||||
|
return cost[k]
|
||||||
|
end
|
||||||
|
|
||||||
|
i = cost.size - 1
|
||||||
|
while i >= 0 do
|
||||||
|
cost[i] += [get(cost, i + 1), get(cost, i + 2)].min
|
||||||
|
i -= 1
|
||||||
|
end
|
||||||
|
|
||||||
|
return cost.take(2).min
|
||||||
|
end
|
||||||
|
|
||||||
|
RSpec.describe "min_cost_climbing_stairs" do
|
||||||
|
it "of [10,15,20] is 15" do
|
||||||
|
expect(min_cost_climbing_stairs([10,15,20])).to eq(15)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "of [1,100,1,1,1,100,1,1,100,1] is 6" do
|
||||||
|
expect(min_cost_climbing_stairs([1,100,1,1,1,100,1,1,100,1])).to eq(6)
|
||||||
|
end
|
||||||
|
end
|
Loading…
Reference in a new issue