A - Frog 1 Editorial by iastm


Let \(f(i)\) be the minimum cost of reaching Stone \(i\). Since the frog is initially on Stone \(1\), \(f(1)=0\). The only way to reach Stone \(2\) is from Stone \(1\), so \(f(2)=|h_1-h_2|\).

For \(i\gt2\), the frog can reach Stone \(i\) from either Stone \(i-1\) or Stone \(i-2\), so \(f(i)=\min(f(i-1)+|h_{i-1}-h_i|, f(i-2)+|h_{i-2}-h_i|)\).

We can implement the above logic using a for-loop to compute \(f(N)\), the minimum cost of reaching Stone \(N\). Since we iterate over \(N\) possible values of \(i\), the time complexity is \(O(N)\).

Sample code (Python):

N = int(input())
H = [int(x) for x in input().split()]

dp = [0] * N
dp[1] = abs(H[0] - H[1])
for i in range(2, N):
    dp[i] = min(
        dp[i - 1] + abs(H[i - 1] - H[i]),
        dp[i - 2] + abs(H[i - 2] - H[i])
    )

print(dp[-1])

posted:
last update: