from dynamic programming DP_A Anyway, I kind of wrote it down and it was Collecting DP. python
def solve(N, heights):
costs = [0] * N
costs[0] = 0
costs[1] = abs(heights[1] - heights[0])
for i in range(2, N):
costs[i] = min(
costs[i - 2] + abs(heights[i] - heights[i - 2]),
costs[i - 1] + abs(heights[i] - heights[i - 1]),
)
return costs[-1]
I dared to write this in DP to be distributed.
def solve(N, heights):
heights += [INF]
costs = [INF] * (N + 1)
costs[0] = 0
for i in range(N - 1):
costs[i + 1] = min(
costs[i + 1],
costs[i] + abs(heights[i + 1] - heights[i]))
costs[i + 2] = min(
costs[i + 2],
costs[i] + abs(heights[i + 2] - heights[i]))
return costs[N - 1]
def solve(N, heights):
costs = [None] * N
costs[0] = 0
costs[1] = abs(heights[1] - heights[0])
def get_cost(i):
if costs[i] != None:
return costs[i]
c = min(
get_cost(i - 2) + abs(heights[i] - heights[i - 2]),
get_cost(i - 1) + abs(heights[i] - heights[i - 1]),
)
costs[i] = c
return c
return get_cost(N - 1)
This page is auto-translated from [/nishio/DP A](https://scrapbox.io/nishio/DP A) using DeepL. If you looks something interesting but the auto-translated English is not good enough to understand it, feel free to let me know at @nishio_en. I'm very happy to spread my thought to non-Japanese readers.