All problems

Problem 465

Frog Jump with K Steps

Easy · 10 pts · Array, Dynamic Programming

Problem

A frog starts on stone 1 of N stones and wants to reach stone N. From stone i it can jump to any of the stones i + 1, i + 2, ..., i + K. Jumping from stone i to stone j costs |height[i] - height[j]| energy. Find the minimum total energy the frog needs to reach the last stone. Let best[j] be the cheapest way to reach stone j; it is the minimum of best[i] + |height[i] - height[j]| over the K stones before j.

Input

First line: N and K. Second line: the N stone heights.

Output

Print the minimum total energy.

Constraints

2 <= N <= 100000; 1 <= K <= 100; 1 <= height <= 10000

Example input

5 3
10 30 40 50 20

Example output

30

Explanation

With K = 3 and heights 10 30 40 50 20, the frog jumps from stone 1 (10) to stone 2 (30) for 20 energy, then from stone 2 to stone 5 (20) for 10 energy. The total is 30.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Weighted Job Scheduling Next: Maximum Units on a Truck