-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimisation_dp.py
38 lines (31 loc) · 1.02 KB
/
optimisation_dp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# find the minimum cost to get to the i-th stair
# where each stair has a cost to step on
# where p is an array of prices for each step by index
def solution(n, k, p):
dp = [9999 for x in range(n + 1)]
dp[0] = 0
for i in range(1, n):
for j in range(1, k):
if i - j < 0:
continue
dp[i] = dp[i] + p[i]
if dp[i - j] + p[i] > dp[i]:
dp[i] = dp[i - j] + p[i]
return dp[n]
# return the cheapest PATH rather than the price
# in this case we need to return an array of int
# that has the indices of the stairs to take
def solution(n, k, p):
dp = [9999 for x in range(n + 1)]
path = [0 for x in range(n + 1)]
dp[0] = 0
for i in range(1, n):
for j in range(1, k):
if i - j < 0:
continue
if dp[i] == 9999:
dp[i] = dp[i] + p[i]
if dp[i - j] + p[i] < dp[i]:
dp[i] = dp[i - j] + p[i]
path[i] = i - j
return [x for x in path if x != 0]