Editorial for Toad
Submitting an official solution before solving the problem yourself is a bannable offence.
Author:
Try working backwards from stone . There are
ways to have reached stone
with a single jump (from
).
Let's define as the minimum cost required to reach stone
from stone
.
Therefore, can be found as the minimum of all
for
in
.
Let's break down the above formula: in order to get to stone , we will choose a stone that is
to the left of
as the previous stone. The total cost is the cost needed to get from stone
to stone
plus the cost to jump from stone
to
.
is the minimum cost after considering every possible previous stone.
You may use either recursion with memoization or dynamic programming to calculate .
Time complexity: .
Sample solution written in Python
(It is recommended to implement the solution yourself before copy-pasting the official solution)
N, k = map(int, input().split())
a = list(map(int, input().split())); a.insert(0, 0) # Make the array 1-indexed
dp = [1000000000] * (N + 1) # Initialize values with a large number to label as unvisited
dp[1] = 0 # Base case: it costs 0 to get to stone 1
for i in range(1, N + 1):
for d in range(1, k + 1):
if i - d < 1: continue # Make sure previous stone is in range
dp[i] = min(dp[i], dp[i - d] + abs(a[i] - a[i - d]))
print(dp[N])
Comments