"use strict";

var _constants = require("constants");

var hasN = true; // has N *only* line
var type = "b";
// a: 2D split
// b: space split
// c: line split
// z: other (only source)
function main(N, p, s) {
  // N, processed data, source
  var max = p.reduce(function (p, c) {
    return p > c ? p : c;
  });
  var div = p.map(function (e) {
    return divisor(e);
  });

  var _loop = function _loop(i) {
    var count = 0;
    div.forEach(function (d) {
      if (d.indexOf(i) >= 0) count++;
    });
    if (count >= div.length - 1) {
      console.log(i);
      return "break";
    }
  };

  for (var i = max; i > 1; i--) {
    var _ret = _loop(i);

    if (_ret === "break") break;
  }
}
function common(a) {
  var line = a.split('\n').slice(0, a.split('\n').length - 1);
  if (hasN) var N = Number(line.shift());
  switch (type) {
    case "a":
      main(N, line.map(function (e) {
        return e.split(' ').map(function (ee) {
          return Number(ee);
        });
      }), a);
      break;
    case "b":
      main(N, line[0].split(' ').map(function (e) {
        return Number(e);
      }), a);
      break;
    case "c":
      main(N, line, a);
      break;
    case "z":
      main(N, null, a);
  }
}
function divisor(num) {
  var results = [];
  for (var i = 2; i <= num; i++) {
    if (num % i == 0) {
      results.push(i);
    }
  }
  return results;
}
common(require("fs").readFileSync("/dev/stdin", "utf8"));


var lines = [];
var result = 0;
var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
});

rl.on('line', function (x) {
    lines.push(x);
});

rl.on('close', function () {
    N = Number(lines[0]);
    A = lines[1].split(" ").map(value => Number(value));

    A.sort((a, b) => a - b);

    for (var i = 0; i < N - 1; i++) {
        result = Math.max(result, A[N - 1] % A[i]);
        if (A[N - 1] === A[i]) { result = A[N - 1] }
    }

    console.log(result);
});

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 300 points

Problem Statement

There are N integers, A_1, A_2, ..., A_N, written on the blackboard.

You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.

Find the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum possible greatest common divisor of the N integers on the blackboard after your move.

Sample Input 1

3
7 6 8

Sample Output 1

2

If we replace 7 with 4, the greatest common divisor of the three integers on the blackboard will be 2, which is the maximum possible value.

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


'use strict'
function Main(input){
  var M=Math.pow(2,50);
  const K=998244353;
  input=input.trim().split(/\s+/).map(x=>x-0);
  var N=input.shift();
  var sum=input.reduce((a,c)=>a+c);
  var half=Math.floor(sum/2);
  var factor=[3];
  for(let i=0;i<N-1;i++){
    factor.push(factor[i]*2%K);
  }

  var dp=[];
  //dp[i][j][k]でinput[0~i]のうちj個を使って合計をkにする場合の数
  for(let i=0;i<=N;i++){
    dp[i]=[];
    for(let j=0;j<=i;j++){
      dp[i][j]=[];
      for(let k=0;k<=half;k++){
        dp[i][j][k]=0;
      }
    }
  }
  dp[0][0][0]=1;
  for(let i=0;i<N;i++){
    for(let j=0;j<=i;j++){
      for(let k=0;k<=half;k++){
        dp[i+1][j][k]+=dp[i][j][k];
        dp[i+1][j][k]%=K;
      }
      for(let k=input[i];k<=half;k++){
        dp[i+1][j+1][k]+=dp[i][j][k-input[i]];
        dp[i+1][j+1][k]%=K;
      }
    }
  }
  var ans=1;
  for(let i=0;i<N;i++){
    ans*=3;
    ans%=K;
  }
  for(let i=0;i<N;i++){
    let p=factor[i];
    let q=dp[N][i].reduce(function(b,c,j){
      if(j<=half)
        b+=c;
        b%=K;
      return b;
    },0)%K;
    let n=Math.round(p*q/M)+1;
    let r=(p-p%n)/n;
    ans-=((r*q%K)*n+(p%n)*q)%K;
  }
  ans%=K;
  ans+=K;
  ans%=K;
  if(sum%2===0){
    for(let j=0;j<=N;j++){
      ans+=3*dp[N][j][half];
      ans%=K;
    }
  }
  console.log(ans);
}

Main(require('fs').readFileSync('/dev/stdin','utf8'));

Score : 600 points

Problem Statement

You are given N integers. The i-th integer is a_i.
Find the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the following condition is satisfied:

Let R, G and B be the sums of the integers painted red, green and blue, respectively. There exists a triangle with positive area whose sides have lengths R, G and B.

Constraints

3 \leq N \leq 300

1 \leq a_i \leq 300(1\leq i\leq N)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

Print the number, modulo 998244353, of ways to paint each of the integers red, green or blue so that the condition is satisfied.

Sample Input 1

4
1
1
1
2

Sample Output 1

18

We can only paint the integers so that the lengths of the sides of the triangle will be 1, 2 and 2, and there are 18 such ways.

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

20
3
1
4
1
5
9
2
6
5
3
5
8
9
7
9
3
2
3
8
4

Sample Output 3

563038556


'use strict'
function Main(input){
  const K=998244353;
  input=input.trim().split(/\s+/).map(x=>x-0);
  var N=input.shift();
  var sum=input.reduce((a,c)=>a+c);
  var half=Math.floor(sum/2);
  var factor=[3];
  for(let i=0;i<N-1;i++){
    factor.push(factor[i]*2%K);
  }

  var dp=[];
  //dp[i][j][k]でinput[0~i]のうちj個を使って合計をkにする場合の数
  for(let i=0;i<=N;i++){
    dp[i]=[];
    for(let j=0;j<=i;j++){
      dp[i][j]=[];
      for(let k=0;k<=sum;k++){
        dp[i][j][k]=0;
      }
    }
  }
  dp[0][0][0]=1;
  for(let i=0;i<N;i++){
    for(let j=0;j<=i;j++){
      for(let k=0;k<=sum;k++){
        dp[i+1][j][k]+=dp[i][j][k];
        dp[i+1][j][k]%=K;
      }
      for(let k=input[i];k<=sum;k++){
        dp[i+1][j+1][k]+=dp[i][j][k-input[i]];
        dp[i+1][j+1][k]%=K;
      }
    }
  }
  var ans=1;
  for(let i=0;i<N;i++){
    ans*=3;
    ans%=K;
  }
  for(let i=0;i<N;i++){
    ans-=factor[i]*dp[N][i].reduce(function(b,c,j){
      if(j<=half)
        b+=c;
        b%=K;
      return b;
    },0)%K;
  }
  while(ans<0)
    ans+=K;
  ans%=K;
  if(sum%2===0){
    for(let j=0;j<=N;j++){
      ans+=3*dp[N][j][half];
      ans%=K;
    }
  }
  console.log(ans);
}

Main(require('fs').readFileSync('/dev/stdin','utf8'));


"use strict";
function Main(input) {
    let cin = new Inputer(input);
    let n = cin.getInt(), a = cin.getIntArray(n);
    const Maxn = 305, p = 998244353;
    let sum = new Array(Maxn); sum[0] = 0;
    let dp = new Array(Maxn * Maxn).fill(0);
    let dp2 = new Array(Maxn * Maxn).fill(0);
    const div2 = (a) => Math.floor(a / 2);
    const div = (a, b) => Math.floor(a / b);

    a.sort((a, b) => a - b);
    a.unshift(0);
    for (let i = 1; i <= n; i++) sum[i] = sum[i - 1] + a[i];
    dp[0] = Math.pow(2, n);
    dp2[0] = 1;
    for (let i = 1; i <= n; i++)
        for (let j = sum[i]; j >= a[i]; j--)
            dp[j] = (dp[j] + 499122177 * dp[j - a[i]] % p) % p,
                dp2[j] = (dp2[j] + dp2[j - a[i]]) % p;
    let ans = 0;
    if (!(sum[n] % 2)) ans += dp[div2(sum[n])] - dp2[div2(sum[n])];
    for (let i = div2(sum[n]) + 1; i <= sum[n]; i++)
        ans = (ans + dp[i]) % p;
    ans *= 3;
    ans = ((Math.pow(3, n) - ans) % p + p) % p;
    console.log(ans);
}
class Inputer{constructor(t){this.cnt=0,this.items=t.split(/\n|\s/)}getInt(){return this.items[this.cnt++]-0}getIntArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getInt();return r}getStr(){return this.items[this.cnt++]}getStrArray(t){let r=new Array(t);for(let e=0;e<t;e++)r[e]=this.getStr();return r}}
if (typeof window == "undefined") Main(require("fs").readFileSync("/dev/stdin", "utf8"));


'use strict'

const main = input => {
	const args = input.trim().split(' ')
	const a = parseInt(args[0], 10)
	const b = parseInt(args[1], 10)
	const c = parseInt(args[2], 10)
	console.log(Math.min(Math.floor(b / a), c))
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))

Score : 100 points

Problem Statement

Takahashi likes the sound when he buys a drink from a vending machine.

That sound can be heard by spending A yen (the currency of Japan) each time.

Takahashi has B yen. He will hear the sound as many times as he can with that money, but at most C times, as he would be satisfied at that time.

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

Print the number of times Takahashi will hear his favorite sound.

Sample Input 1

2 11 4

Sample Output 1

4

Since he has not less than 8 yen, he will hear the sound four times and be satisfied.

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var S = inputStr[0];
  var i = 0;
  var counter = 0;
  var tmp = "";

  while(S.length >= 2 && i+1 < S.length ){
    //console.log('i=$1',i);
    if (S.substr(i,1) != S.substr(i+1,1) ){
      //console.log(S.substr(i,1));
      //console.log(S.substr(i+1,1));

	  //console.log("捨てる");
      //iとi+1番目の配列要素を捨てる
	  tmp = S.substr(1,i) + S.substr(i+2)
      S = tmp;
      //console.log(tmp);
      counter += 2;
      i -= 1;	//一つ前の要素から
    } else {
      //次の要素に進める
      i += 1;
    }
  }
  console.log(counter);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var A = Number.parseInt(inputStr[0]);
  var B = Number.parseInt(inputStr[1]);
  var C = Number.parseInt(inputStr[2]);
  var i = 0;

  while( (B - (A*(i+1)) > 0) && ((i+1) <= C) ){
    i += 1;
  }
  console.log(i);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
	inputs = input.split(' ');
    x = Math.floor(inputs[1] / inputs[0]);
    if(x >= inputs[2]){
    console.log(inputs[2]);
    }else if(x <= inputs[2]){
    console.log(x);
    }
}
Main(require("fs").readFileSync("/dev/stdin","utf8"));


    function main(arg){
      let args = arg.split(" ");
      let ans = 0;
      if( Number(args[0])*Number(args[2]) <= Number(args[1]) ){
        ans = Number(args[2]);
      }
      console.log(ans);
    }

    main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input){
	var temp = input.split(" ");
	var A = parseInt(temp[0]);
	var B = parseInt(temp[1]);
	var C = parseInt(temp[2]);

	var count = Math.floor(B/A);
	if(count > C) count = C;
	console.log(count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// parameter "input" gets all data
function FavoriteSound(input) {
    // the first line is assigned to input[0], the second line is assigned to input[1] similarly.
    var _a = input.split("\n")[0].split(" ").map(Number), A = _a[0], B = _a[1], C = _a[2];
    // convert string from integer using "parseInt"
    var count = Math.min(C, Math.floor(B / A));
    //output
    console.log('%d', count);
}
exports.FavoriteSound = FavoriteSound;
// Don't edit this line!
try {
    FavoriteSound(require("fs").readFileSync("/dev/stdin", "utf8"));
}
catch (e) {
    // ignore, so importing in local unit tests would work
}
//# sourceMappingURL=FavoriteSound.js.map


function Main(input) {
	tmp = input.split("\n")[0].split(" ");
	var a = parseInt(tmp[0], 10);
	var b = parseInt(tmp[1], 10);
	var c = parseInt(tmp[2], 10);
	console.log(Math.min(c, a/b));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  var inputList = input.split(" ");
  var charge = Number(inputList[0]);
  var have = Number(inputList[1]);
  var max = Number(inputList[2]);
  var listenMax = Math.floor(have / charge);

  const ans = max > listenMax ? listenMax : max;
  console.log(ans);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

const main = arg => {
    const A = parseInt(arg.split("\n")[0].split(" ")[0]);
    const B = parseInt(arg.split("\n")[0].split(" ")[1]);
    const C = parseInt(arg.split("\n")[0].split(" ")[2]);
    console.log(Math.floor(B / A) >= C ? C : Math.floor(B / A));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict"
function Main(input){
 input=input.trim();
 input=input.split(/\s+/);
 for(let i=0;i<input.length;i++)
   input[i]=input[i]-0;
  var A=input[0];
  var B=input[1];
  var C=input[2];
  var M=Math.floor(B/A);
  var result=Math.min(M,C);
  console.log(result);
}

Main(require("fs").readFileSync("/dev/stdin","utf8"));


// inputに入力データ全体が入る
function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.split("\n")
  tmp0 = input[0].split(" ")
  A = Number(tmp0[0])
  B = Number(tmp0[1])
  C = Number(tmp0[2])

  console.log(Math.min(Math.floor(B/A), C))

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main("100 1 10\n")


process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function ti(a){
    for(let i = 0; i < a.length; i++)
        a[i] = parseInt(a[i]);

    return a;
}

function main(){
    let [n,k] = ti(readline().split(' '));
    let h = ti(readline().split(' '));

    let dp = new Array(n);
    dp.fill(999999999999999);
    dp[0] = 0;
    for(let i = 0; i < n; i++){
        for(let j = 1; j < k+1; j++){
            if(i-j >= 0)
                dp[i] = Math.min(dp[i], Math.abs(h[i]-h[i-j]) + dp[i-j]);
            else
                break;
        }
    }

    console.log(dp[n-1]);
}

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

If we follow the path 1 → 2 → 4, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

2
10 10

Sample Output 2

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

If we follow the path 1 → 3 → 5 → 6, the total cost incurred would be |30 - 60| + |60 - 60| + |60 - 50| = 40.


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});

    let N = parseInt(input[0][0], 10);
    let v_h = input[1].map(e => parseInt(e, 10));

    let DP = [0, Math.abs(v_h[1] - v_h[0])];

    let x1, x2;
    for(let i = 2; i < N; i++){
        x1 = DP[i - 2] + Math.abs(v_h[i] - v_h[i - 2]);
        x2 = DP[i - 1] + Math.abs(v_h[i] - v_h[i - 1]);
        DP.push(Math.min(x1, x2));
    }

    console.log(DP[N - 1]);

}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");

const N = input[0].split(' ').map(item => parseInt(item))[0]
const H = input[1].split(' ').map(item => parseInt(item))

dp = new Array()
// console.log(dp)

const dfs = (pos) => {
    // console.log(pos, dp)
    if (dp[pos]) return dp[pos]
    if (pos == 0) return dp[pos] = 0
    if (pos == 1) return dp[pos] = dfs(pos-1) + Math.abs(H[pos] - H[pos-1])
    step1 = dfs(pos-1) + Math.abs(H[pos] - H[pos-1])
    step2 = dfs(pos-2) + Math.abs(H[pos] - H[pos-2])
    return dp[pos] = Math.min(step1, step2)
}

console.log(dfs(N-1))
// console.log(dp)


const input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");

const N = input[0].split(' ').map(item => parseInt(item))[0]
const H = input[1].split(' ').map(item => parseInt(item))

dp = new Array(N)
// console.log(dp)

const dfs = (pos) => {
    // console.log(pos, dp)
    if (dp[pos]) return dp[pos]
    if (pos == 0) return dp[pos] = 0
    if (pos == 1) {
        return dp[pos] = dfs(pos-1) + Math.abs(H[1] - H[0])
    }
    step1 = dfs(pos-1) + Math.abs(H[pos] - H[pos-1])
    step2 = dfs(pos-2) + Math.abs(H[pos] - H[pos-2])
    return dp[pos] = Math.min(step1, step2)
}

console.log(dfs(N-1))
// console.log(dp)


const input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n");

const N = input[0].split(' ').map(item => parseInt(item))[0]
const H = input[1].split(' ').map(item => parseInt(item))

dp = new Array(N)
// console.log(dp)

const dfs = (pos) => {
    if (dp[pos]) return dp[pos]
    if (pos == 0) return dp[pos] = 0
    if (pos == 1) {
        if (!dp[0]) dp[0] = dfs(0)
        return dp[pos] = Math.abs(H[1] - H[0])
    }
    if (pos >= 2) {
        if (!dp[pos-1]) dp[pos-1] = dfs(pos-1)
        if (!dp[pos-2]) dp[pos-2] = dfs(pos-2)
        step1 = dfs(pos-1) + Math.abs(H[pos] - H[pos-1])
        step2 = dfs(pos-2) + Math.abs(H[pos] - H[pos-2])
        return dp[pos] = Math.min(step1, step2)
    }
}

console.log(dfs(N-1))
// console.log(dp)


'use strict';
process.stdin.resume();
process.stdin.setEncoding('utf8');

// Your code here!
const max = (a)=>{
    let i = a.length;
    let max=-Infinity;
    while (i--) {
        if (a[i] > max)max = a[i];
    }
    return max;
}
const min = (a)=>{
    let i = a.length;
    let max=Infinity;
    while (i--) {
        if (a[i] < max)max = a[i];
    }
    return max;
}
const Main = (p)=>{
	// 1行目がinput[0], 2行目がinput[1], …に入る
	p = p.split("\n");
	//let N = parseInt(p[0].split(" ")[0]);
	let N = parseInt(p[0]);
	//let M = parseInt(p[0].split(" ")[1]);
	let h = (p[1].split(" ").map(Number));
	let i = N;
// 	while(i--){
// 	    h[i]=Math.floor(Math.random() * 100);
// 	}
	let c = new Array(N).fill(Infinity);
	//console.log(h)
    c[0]=0;
    c[1]=Math.abs(h[0]-h[1]);
    for(i=2;i<N;i++){
        c[i]=Math.min(c[i-2]+Math.abs(h[i]-h[i-2]),c[i-1]+Math.abs(h[i]-h[i-1]));
    }
	//文字列から10進数に変換するときはparseIntを使います
	console.log(c[N-1]);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function main(arg) {
  arg = arg.split("\n");
  var arr = arg[1].split(" ").map(Number);
  var dp = [0, Math.abs(arr[1] - arr[0])]
  for (var i=2; i<arr.length; i++) {
    dp[i] = Math.min(Math.abs(arr[i] - arr[i-1]) + dp[i-1], Math.abs(arr[i] - arr[i-2]) + dp[i-2])
  }
  console.log(dp[dp.length-1])
}
main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


var inputRaw = require('fs').readFileSync('/dev/stdin', 'utf8')
var rows = inputRaw.trim().split('\n');
var N = Number(rows[0]);
var h = rows[1].split(' ').map(Number);
var dp = Array(N).fill(0);

function solve() {
  for (var i = 0; i < N - 1; i++) {
    if (i <= 0) {
      dp[i + 2] = Math.abs(h[i] - h[i + 1]);
    } else {
      var a = dp[i + 1] + Math.abs(h[i] - h[i + 1]);
      var b = dp[i] + Math.abs(h[i - 1] - h[i + 1]);
      dp[i + 2] = Math.min(a, b);
    }
  }
  return dp[N];
}

console.log(solve());


'use strict';
function min(a, b){
  return a > b ? b : a;
}

function Main(inputs) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  const input = inputs.split("\n");
  const n = Number(input[0]);
  const h = input[1].split(' ');
  const dp = Array(n).fill(1e10);
  dp[0] = 0;

  for (let i = 0; i < n - 1; i++) {
    dp[i + 1] = min(dp[i + 1], dp[i] + Math.abs(h[i] - h[i + 1]));
    dp[i + 2] = min(dp[i + 2], dp[i] + Math.abs(h[i] - h[i + 2]));
  }
  dp[n - 1] = min(dp[n - 1], dp[n - 2] + Math.abs(h[n - 2] - h[n - 1]));
  console.log(dp[n - 1]);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main (stones) {
  const dp = Array(stones.length).fill(Infinity)
  dp[0] = 0
  for (let i = 0; i < stones.length; i++) {
    for(let j = i + 1; j <= i + 2; j++ ) {
      if (j < stones.length) {
        dp[j] = Math.min(dp[j], dp[i] + Math.abs(stones[i] - stones[j]))
      }
    }
  }
  console.log('%d',dp[stones.length - 1])
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


let Main = function (stones) {
  const dp = Array(stones.length).fill(Infinity)
  dp[0] = 0
  for (let i = 0; i < stones.length; i++) {
    for(let j = i + 1; j <= i + 2; j++ ) {
      if (j < stones.length) {
        dp[j] = Math.min(dp[j], dp[i] + Math.abs(stones[i] - stones[j]))
      }
    }
  }
  return dp[stones.length - 1]
}


process.stdin.resume();
process.stdin.setEncoding('utf8');

var input_stdin = '';
var chunks = '';

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    chunks = input_stdin.split('');
    start();
});

function start() {
	console.log(chunks[0]);
  	return chunks[1];
}


function Main(input){
  //パラメータ受け取り
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  inputStr = input[1].split(" ");
  var H_arr = inputStr.map( inputStr => parseInt(inputStr));

  //解法として貪欲法を用いる
  var i = 0;	//今たっている場所
  var ans = []; //回答格納用配列
  //階段の0段目のコストをメモ。値は0
  ans.push(0);
  //階段の1段目に進んだ時のコストをメモ
  ans.push(Math.abs(H_arr[1]-H_arr[0]));
　//階段の3段目以降のコストをforループで処理を回して産出し続ける
  for( var i=2 ; i<N ; i++){
    var v1 = ans[i-1]+Math.abs(H_arr[i]-H_arr[i-1]);
    var v2 = ans[i-2]+Math.abs(H_arr[i]-H_arr[i-2]);
    ans.push(Math.min(v1,v2));
  }
  //結果表示
  console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var n={};!function(t){"use strict";(n["Control.Apply"]=n["Control.Apply"]||{}).arrayApply=function(n){return function(t){for(var r=n.length,e=t.length,u=new Array(r*e),i=0,o=0;o<r;o++)for(var a=n[o],f=0;f<e;f++)u[i++]=a(t[f]);return u}}}(),function(n){"use strict";n["Control.Semigroupoid"]=n["Control.Semigroupoid"]||{};var t=n["Control.Semigroupoid"],r=function(n){this.compose=n},e=new r(function(n){return function(t){return function(r){return n(t(r))}}});t.compose=function(n){return n.compose},t.Semigroupoid=r,t.semigroupoidFn=e}(n),function(n){"use strict";n["Control.Category"]=n["Control.Category"]||{};var t=n["Control.Category"],r=n["Control.Semigroupoid"],e=function(n,t){this.Semigroupoid0=n,this.identity=t},u=new e(function(){return r.semigroupoidFn},function(n){return n});t.Category=e,t.identity=function(n){return n.identity},t.categoryFn=u}(n),function(n){"use strict";n["Data.Function"]=n["Data.Function"]||{};var t=n["Data.Function"];t.flip=function(n){return function(t){return function(r){return n(r)(t)}}},t.const=function(n){return function(t){return n}}}(n),function(t){"use strict";(n["Data.Functor"]=n["Data.Functor"]||{}).arrayMap=function(n){return function(t){for(var r=t.length,e=new Array(r),u=0;u<r;u++)e[u]=n(t[u]);return e}}}(),function(t){"use strict";(n["Data.Unit"]=n["Data.Unit"]||{}).unit={}}(),function(n){"use strict";n["Data.Unit"]=n["Data.Unit"]||{};var t=n["Data.Unit"],r=n["Data.Unit"];t.unit=r.unit}(n),function(n){"use strict";n["Data.Functor"]=n["Data.Functor"]||{};var t=n["Data.Functor"],r=n["Data.Functor"],e=n["Data.Function"],u=n["Data.Unit"],i=function(n){this.map=n},o=function(n){return n.map},a=new i(r.arrayMap);t.Functor=i,t.map=o,t.void=function(n){return o(n)(e.const(u.unit))},t.functorArray=a}(n),function(n){"use strict";n["Control.Apply"]=n["Control.Apply"]||{};var t=n["Control.Apply"],r=n["Control.Apply"],e=n["Control.Category"],u=n["Data.Function"],i=n["Data.Functor"],o=function(n,t){this.Functor0=n,this.apply=t},a=new o(function(){return i.functorArray},r.arrayApply),f=function(n){return n.apply};t.Apply=o,t.apply=f,t.applySecond=function(n){return function(t){return function(r){return f(n)(i.map(n.Functor0())(u.const(e.identity(e.categoryFn)))(t))(r)}}},t.applyArray=a}(n),function(n){"use strict";n["Control.Applicative"]=n["Control.Applicative"]||{};var t=n["Control.Applicative"],r=n["Control.Apply"],e=function(n){return n.pure};t.Applicative=function(n,t){this.Apply0=n,this.pure=t},t.pure=e,t.liftA1=function(n){return function(t){return function(u){return r.apply(n.Apply0())(e(n)(t))(u)}}}}(n),function(t){"use strict";(n["Control.Bind"]=n["Control.Bind"]||{}).arrayBind=function(n){return function(t){for(var r=[],e=0,u=n.length;e<u;e++)Array.prototype.push.apply(r,t(n[e]));return r}}}(),function(n){"use strict";n["Control.Bind"]=n["Control.Bind"]||{};var t=n["Control.Bind"],r=n["Control.Bind"],e=n["Control.Apply"],u=n["Data.Function"],i=function(n,t){this.Apply0=n,this.bind=t},o=new i(function(){return e.applyArray},r.arrayBind),a=function(n){return n.bind},f=function(n){return u.flip(a(n))};t.Bind=i,t.bind=a,t.bindFlipped=f,t.composeKleisliFlipped=function(n){return function(t){return function(r){return function(e){return f(n)(t)(r(e))}}}},t.bindArray=o}(n),function(n){"use strict";n["Control.Monad"]=n["Control.Monad"]||{};var t=n["Control.Monad"],r=n["Control.Applicative"],e=n["Control.Bind"];t.Monad=function(n,t){this.Applicative0=n,this.Bind1=t},t.ap=function(n){return function(t){return function(u){return e.bind(n.Bind1())(t)(function(t){return e.bind(n.Bind1())(u)(function(e){return r.pure(n.Applicative0())(t(e))})})}}}}(n),function(n){"use strict";n.map_=function(n){return function(t){return function(){return n(t())}}},n.pure_=function(n){return function(){return n}},n.bind_=function(n){return function(t){return function(){return t(n())()}}},n.for=function(n){return function(t){return function(r){return function(){for(var e=n;e<t;e++)r(e)()}}}}}(n["Control.Monad.ST.Internal"]=n["Control.Monad.ST.Internal"]||{}),function(n){"use strict";n["Control.Monad.ST.Internal"]=n["Control.Monad.ST.Internal"]||{};var t=n["Control.Monad.ST.Internal"],r=n["Control.Monad.ST.Internal"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=new n["Data.Functor"].Functor(r.map_),f=new o.Monad(function(){return s},function(){return c}),c=new i.Bind(function(){return l},r.bind_),l=new u.Apply(function(){return a},o.ap(f)),s=new e.Applicative(function(){return l},r.pure_);t.functorST=a,t.applyST=l,t.applicativeST=s,t.bindST=c,t.monadST=f,t.for=r.for}(n),function(n){"use strict";n["Control.Parallel.Class"]=n["Control.Parallel.Class"]||{};var t=n["Control.Parallel.Class"];t.parallel=function(n){return n.parallel},t.sequential=function(n){return n.sequential},t.Parallel=function(n,t,r,e){this.Applicative1=n,this.Monad0=t,this.parallel=r,this.sequential=e}}(n),function(n){"use strict";n.foldrArray=function(n){return function(t){return function(r){for(var e=t,u=r.length-1;u>=0;u--)e=n(r[u])(e);return e}}},n.foldlArray=function(n){return function(t){return function(r){for(var e=t,u=r.length,i=0;i<u;i++)e=n(e)(r[i]);return e}}}}(n["Data.Foldable"]=n["Data.Foldable"]||{}),function(n){"use strict";n["Data.Monoid"]=n["Data.Monoid"]||{};var t=n["Data.Monoid"];t.Monoid=function(n,t){this.Semigroup0=n,this.mempty=t},t.mempty=function(n){return n.mempty}}(n),function(n){"use strict";n["Data.Semigroup"]=n["Data.Semigroup"]||{};var t=n["Data.Semigroup"];t.Semigroup=function(n){this.append=n},t.append=function(n){return n.append}}(n),function(n){"use strict";n["Data.Foldable"]=n["Data.Foldable"]||{};var t=n["Data.Foldable"],r=n["Data.Foldable"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Data.Monoid"],o=n["Data.Semigroup"],a=n["Data.Unit"],f=function(n,t,r){this.foldMap=n,this.foldl=t,this.foldr=r},c=function(n){return n.foldr},l=function(n){return function(t){return function(r){return c(n)(function(n){return function(e){return o.append(t.Semigroup0())(r(n))(e)}})(i.mempty(t))}}},s=new f(function(n){return l(s)(n)},r.foldlArray,r.foldrArray);t.Foldable=f,t.foldr=c,t.foldl=function(n){return n.foldl},t.foldMap=function(n){return n.foldMap},t.foldMapDefaultR=l,t.traverse_=function(n){return function(t){return function(r){return c(t)(function(t){return u.applySecond(n.Apply0())(r(t))})(e.pure(n)(a.unit))}}},t.foldableArray=s}(n),function(n){"use strict";n["Control.Parallel"]=n["Control.Parallel"]||{};var t=n["Control.Parallel"],r=n["Control.Category"],e=n["Control.Parallel.Class"],u=n["Data.Foldable"],i=function(n){return function(t){return function(r){return function(i){return e.sequential(n)(u.traverse_(n.Applicative1())(t)(function(t){return e.parallel(n)(r(t))})(i))}}}};t.parTraverse_=i,t.parSequence_=function(n){return function(t){return i(n)(t)(r.identity(r.categoryFn))}}}(n),function(n){"use strict";n.replicate="function"==typeof Array.prototype.fill?function(n){return function(t){return n<1?[]:new Array(n).fill(t)}}:function(n){return function(t){for(var r=[],e=0,u=0;u<n;u++)r[e++]=t;return r}},n.length=function(n){return n.length}}(n["Data.Array"]=n["Data.Array"]||{}),function(n){"use strict";n["Data.Maybe"]=n["Data.Maybe"]||{};var t=n["Data.Maybe"],r=function(){function n(){}return n.value=new n,n}(),e=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}();t.Nothing=r,t.Just=e,t.maybe=function(n){return function(t){return function(u){if(u instanceof r)return n;if(u instanceof e)return t(u.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[n.constructor.name,t.constructor.name,u.constructor.name])}}},t.fromJust=function(n){return function(n){if(n instanceof e)return n.value0;throw new Error("Failed pattern match at Data.Maybe (line 268, column 1 - line 268, column 46): "+[n.constructor.name])}}}(n),function(n){"use strict";n["Data.Array"]=n["Data.Array"]||{};var t=n["Data.Array"],r=n["Data.Array"],e=n["Control.Bind"],u=n["Data.Function"],i=n["Data.Maybe"],o=function(n){return[n]},a=u.flip(e.bind(e.bindArray));t.singleton=o,t.concatMap=a,t.mapMaybe=function(n){return a(function(t){return i.maybe([])(o)(n(t))})},t.replicate=r.replicate,t.length=r.length}(n),function(n){"use strict";n["Data.Array.Partial"]=n["Data.Array.Partial"]||{};var t=n["Data.Array.Partial"],r=n["Data.Array"];t.head=function(n){return function(n){return n[0]}},t.last=function(n){return function(n){return n[r.length(n)-1|0]}}}(n),function(n){"use strict";n.peekImpl=function(n){return function(t){return function(r){return function(e){return function(){return r>=0&&r<e.length?n(e[r]):t}}}}},n.poke=function(n){return function(t){return function(r){return function(){var e=n>=0&&n<r.length;return e&&(r[n]=t),e}}}}}(n["Data.Array.ST"]=n["Data.Array.ST"]||{}),function(n){"use strict";n["Data.Array.ST"]=n["Data.Array.ST"]||{};var t=n["Data.Array.ST"],r=n["Data.Array.ST"],e=n["Control.Applicative"],u=n["Control.Monad.ST.Internal"],i=n["Data.Maybe"],o=r.peekImpl(i.Just.create)(i.Nothing.value);t.peek=o,t.unsafeThaw=function(n){return e.pure(u.applicativeST)(n)},t.poke=r.poke}(n),function(n){"use strict";n["Data.Either"]=n["Data.Either"]||{};var t=n["Data.Either"],r=n["Control.Applicative"],e=n["Control.Apply"],u=n["Control.Bind"],i=n["Data.Functor"],o=n["Data.Maybe"],a=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),f=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),c=new i.Functor(function(n){return function(t){if(t instanceof a)return new a(t.value0);if(t instanceof f)return new f(n(t.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[t.constructor.name])}}),l=function(n){return function(t){return function(r){if(r instanceof a)return n(r.value0);if(r instanceof f)return t(r.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[n.constructor.name,t.constructor.name,r.constructor.name])}}},s=new e.Apply(function(){return c},function(n){return function(t){if(n instanceof a)return new a(n.value0);if(n instanceof f)return i.map(c)(n.value0)(t);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[n.constructor.name,t.constructor.name])}}),p=new u.Bind(function(){return s},l(function(n){return function(t){return new a(n)}})(function(n){return function(t){return t(n)}})),d=new r.Applicative(function(){return s},f.create);t.Left=a,t.Right=f,t.either=l,t.note=function(n){return o.maybe(new a(n))(f.create)},t.functorEither=c,t.applyEither=s,t.applicativeEither=d,t.bindEither=p}(n),function(t){"use strict";(n["Data.Int"]=n["Data.Int"]||{}).fromStringAsImpl=function(n){return function(t){return function(r){var e;e=r<11?"[0-"+(r-1).toString()+"]":11===r?"[0-9a]":"[0-9a-"+String.fromCharCode(86+r)+"]";var u=new RegExp("^[\\+\\-]?"+e+"+$","i");return function(e){if(u.test(e)){var i=parseInt(e,r);return(0|i)===i?n(i):t}return t}}}}}(),function(n){"use strict";n["Data.Int"]=n["Data.Int"]||{};var t=n["Data.Int"],r=n["Data.Int"],e=n["Data.Maybe"],u=r.fromStringAsImpl(e.Just.create)(e.Nothing.value),i=u(10);t.fromString=i,t.fromStringAs=u}(n),function(t){"use strict";(n["Data.Eq"]=n["Data.Eq"]||{}).refEq=function(n){return function(t){return n===t}}}(),function(n){"use strict";n["Data.Eq"]=n["Data.Eq"]||{};var t=n["Data.Eq"],r=function(n){this.eq=n},e=new r(n["Data.Eq"].refEq);t.Eq=r,t.eq=function(n){return n.eq},t.eqInt=e}(n),function(t){"use strict";(n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{}).unsafeCompareImpl=function(n){return function(t){return function(r){return function(e){return function(u){return e<u?n:e===u?t:r}}}}}}(),function(n){"use strict";n["Data.Ordering"]=n["Data.Ordering"]||{};var t=n["Data.Ordering"],r=function(){function n(){}return n.value=new n,n}(),e=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}();t.LT=r,t.GT=e,t.EQ=u}(n),function(n){"use strict";n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{};var t=n["Data.Ord.Unsafe"],r=n["Data.Ord.Unsafe"],e=n["Data.Ordering"],u=r.unsafeCompareImpl(e.LT.value)(e.EQ.value)(e.GT.value);t.unsafeCompare=u}(n),function(t){"use strict";(n["Data.Ring"]=n["Data.Ring"]||{}).intSub=function(n){return function(t){return n-t|0}}}(),function(n){"use strict";n.intAdd=function(n){return function(t){return n+t|0}},n.intMul=function(n){return function(t){return n*t|0}}}(n["Data.Semiring"]=n["Data.Semiring"]||{}),function(n){"use strict";n["Data.Semiring"]=n["Data.Semiring"]||{};var t=n["Data.Semiring"],r=n["Data.Semiring"],e=function(n,t,r,e){this.add=n,this.mul=t,this.one=r,this.zero=e},u=new e(r.intAdd,r.intMul,1,0);t.Semiring=e,t.add=function(n){return n.add},t.zero=function(n){return n.zero},t.mul=function(n){return n.mul},t.one=function(n){return n.one},t.semiringInt=u}(n),function(n){"use strict";n["Data.Ring"]=n["Data.Ring"]||{};var t=n["Data.Ring"],r=n["Data.Ring"],e=n["Data.Semiring"],u=function(n,t){this.Semiring0=n,this.sub=t},i=function(n){return n.sub},o=new u(function(){return e.semiringInt},r.intSub);t.Ring=u,t.sub=i,t.negate=function(n){return function(t){return i(n)(e.zero(n.Semiring0()))(t)}},t.ringInt=o}(n),function(n){"use strict";n["Data.Ord"]=n["Data.Ord"]||{};var t=n["Data.Ord"],r=n["Data.Eq"],e=n["Data.Ord.Unsafe"],u=n["Data.Ordering"],i=n["Data.Ring"],o=n["Data.Semiring"],a=function(n,t){this.Eq0=n,this.compare=t},f=new a(function(){return r.eqInt},e.unsafeCompare),c=function(n){return n.compare},l=function(n){return function(t){return function(r){return!(c(n)(t)(r)instanceof u.LT)}}};t.Ord=a,t.compare=c,t.greaterThanOrEq=l,t.min=function(n){return function(t){return function(r){var e=c(n)(t)(r);if(e instanceof u.LT)return t;if(e instanceof u.EQ)return t;if(e instanceof u.GT)return r;throw new Error("Failed pattern match at Data.Ord (line 119, column 3 - line 122, column 12): "+[e.constructor.name])}}},t.abs=function(n){return function(t){return function(r){return l(n)(r)(o.zero(t.Semiring0()))?r:i.negate(t)(r)}}},t.ordInt=f}(n),function(t){"use strict";(n["Data.Show"]=n["Data.Show"]||{}).showIntImpl=function(n){return n.toString()}}(),function(n){"use strict";n["Data.Show"]=n["Data.Show"]||{};var t=n["Data.Show"],r=function(n){this.show=n},e=new r(n["Data.Show"].showIntImpl);t.Show=r,t.show=function(n){return n.show},t.showInt=e}(n),function(n){"use strict";n.split=function(n){return function(t){return t.split(n)}},n.trim=function(n){return n.trim()}}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(n){"use strict";n["Data.String.Common"]=n["Data.String.Common"]||{};var t=n["Data.String.Common"],r=n["Data.String.Common"];t.split=r.split,t.trim=r.trim}(n),function(n){"use strict";n.pureE=function(n){return function(){return n}},n.bindE=function(n){return function(t){return function(){return t(n())()}}}}(n.Effect=n.Effect||{}),function(n){"use strict";n.Effect=n.Effect||{};var t=n.Effect,r=n.Effect,e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=n["Data.Functor"],f=new o.Monad(function(){return s},function(){return c}),c=new i.Bind(function(){return l},r.bindE),l=new u.Apply(function(){return p},o.ap(f)),s=new e.Applicative(function(){return l},r.pureE),p=new a.Functor(e.liftA1(s));t.functorEffect=p,t.applyEffect=l,t.applicativeEffect=s,t.bindEffect=c,t.monadEffect=f}(n),function(n){"use strict";var t=function(){var n={},t="Pure",r="Throw",e="Catch",u="Sync",i="Async",o="Bind",a="Bracket",f="Fork",c="Sequential",l="Map",s="Apply",p="Alt",d="Cons",h="Resume",m="Release",w="Finalizer",v="Finalized",g="Forked";function D(n,t,r,e){this.tag=n,this._1=t,this._2=r,this._3=e}function y(n){var t=function(t,r,e){return new D(n,t,r,e)};return t.tag=n,t}function A(n){return new D(t,void 0)}function E(n){try{n()}catch(t){setTimeout(function(){throw t},0)}}function C(n,t,r){try{return t(r())}catch(e){return n(e)}}function S(n,t,r){try{return t(r)()}catch(e){return r(n(e))(),A}}var _=function(){var n=1024,t=0,r=0,e=new Array(n),u=!1;function i(){var i;for(u=!0;0!==t;)t--,i=e[r],e[r]=void 0,r=(r+1)%n,i();u=!1}return{isDraining:function(){return u},enqueue:function(o){var a;t===n&&(a=u,i(),u=a),e[(r+t)%n]=o,t++,u||i()}}}();var b=0,F=1,P=2,k=3,M=4,I=5,T=6;function B(n,l,s){var p=0,g=b,y=s,A=null,U=null,N=null,L=null,q=null,O=0,x=0,W=null,z=!0;function J(s){for(var x,G,K;;)switch(x=null,G=null,K=null,g){case P:g=F,y=N(y),null===L?N=null:(N=L._1,L=L._2);break;case k:n.isLeft(y)?(g=I,A=y,y=null):null===N?g=I:(g=P,y=n.fromRight(y));break;case F:switch(y.tag){case o:N&&(L=new D(d,N,L)),N=y._2,g=F,y=y._1;break;case t:null===N?(g=I,y=n.right(y._1)):(g=P,y=y._1);break;case u:g=k,y=C(n.left,n.right,y._1);break;case i:return g=M,void(y=S(n.left,y._1,function(n){return function(){p===s&&(p++,_.enqueue(function(){p===s+1&&(g=k,y=n,J(p))}))}}));case r:g=I,A=n.left(y._1),y=null;break;case e:q=new D(d,y,null===N?q:new D(d,new D(h,N,L),q,U),U),N=null,L=null,g=F,y=y._1;break;case a:O++,q=new D(d,y,null===N?q:new D(d,new D(h,N,L),q,U),U),N=null,L=null,g=F,y=y._1;break;case f:g=k,x=B(n,l,y._2),l&&l.register(x),y._1&&x.run(),y=n.right(x);break;case c:g=F,y=R(n,l,y._1)}break;case I:if(N=null,L=null,null===q)g=T,y=U||A||y;else switch(x=q._3,K=q._1,q=q._2,K.tag){case e:U&&U!==x&&0===O?g=I:A&&(g=F,y=K._2(n.fromLeft(A)),A=null);break;case h:U&&U!==x&&0===O||A?g=I:(N=K._1,L=K._2,g=P,y=n.fromRight(y));break;case a:O--,null===A&&(G=n.fromRight(y),q=new D(d,new D(m,K._2,G),q,x),(U===x||O>0)&&(g=F,y=K._3(G)));break;case m:q=new D(d,new D(v,y,A),q,U),g=F,y=U&&U!==x&&0===O?K._1.killed(n.fromLeft(U))(K._2):A?K._1.failed(n.fromLeft(A))(K._2):K._1.completed(n.fromRight(y))(K._2),A=null,O++;break;case w:O++,q=new D(d,new D(v,y,A),q,U),g=F,y=K._1;break;case v:O--,g=I,y=K._1,A=K._2}break;case T:for(var Q in W)W.hasOwnProperty(Q)&&(z=z&&W[Q].rethrow,E(W[Q].handler(y)));return W=null,void(U&&A?setTimeout(function(){throw n.fromLeft(A)},0):n.isLeft(y)&&z&&setTimeout(function(){if(z)throw n.fromLeft(y)},0));case b:g=F;break;case M:return}}function G(n){return function(){if(g===T)return z=z&&n.rethrow,n.handler(y)(),function(){};var t=x++;return(W=W||{})[t]=n,function(){null!==W&&delete W[t]}}}return{kill:function(t,r){return function(){if(g===T)return r(n.right(void 0))(),function(){};var e=G({rethrow:!1,handler:function(){return r(n.right(void 0))}})();switch(g){case b:U=n.left(t),g=T,y=U,J(p);break;case M:null===U&&(U=n.left(t)),0===O&&(g===M&&(q=new D(d,new D(w,y(t)),q,U)),g=I,y=null,A=null,J(++p));break;default:null===U&&(U=n.left(t)),0===O&&(g=I,y=null,A=null)}return e}},join:function(n){return function(){var t=G({rethrow:!1,handler:n})();return g===b&&J(p),t}},onComplete:G,isSuspended:function(){return g===b},run:function(){g===b&&(_.isDraining()?J(p):_.enqueue(function(){J(p)}))}}}function U(t,r,e,u){var o=0,a={},f=0,c={},h=new Error("[ParAff] Early exit"),m=null,w=n;function v(r,e,u){var i,o,f=e,c=null,h=null,m=0,w={};n:for(;;)switch(i=null,f.tag){case g:if(f._3===n&&(i=a[f._1],w[m++]=i.kill(r,function(n){return function(){0===--m&&u(n)()}})),null===c)break n;f=c._2,null===h?c=null:(c=h._1,h=h._2);break;case l:f=f._2;break;case s:case p:c&&(h=new D(d,c,h)),c=f,f=f._1}if(0===m)u(t.right(void 0))();else for(o=0,i=m;o<i;o++)w[o]=w[o]();return w}function y(r){return function(e){return function(){delete a[r._1],r._3=e,function r(e,i,o){var a,d,w,g,D,y;for(t.isLeft(e)?(a=e,d=null):(d=e,a=null);;){if(w=null,g=null,D=null,y=null,null!==m)return;if(null===i)return void u(a||d)();if(i._3!==n)return;switch(i.tag){case l:null===a?(i._3=t.right(i._1(t.fromRight(d))),d=i._3):i._3=a;break;case s:if(w=i._1._3,g=i._2._3,a){if(i._3=a,D=!0,y=f++,c[y]=v(h,a===w?i._2:i._1,function(){return function(){delete c[y],D?D=!1:null===o?r(a,null,null):r(a,o._1,o._2)}}),D)return void(D=!1)}else{if(w===n||g===n)return;d=t.right(t.fromRight(w)(t.fromRight(g))),i._3=d}break;case p:if(w=i._1._3,g=i._2._3,w===n&&t.isLeft(g)||g===n&&t.isLeft(w))return;if(w!==n&&t.isLeft(w)&&g!==n&&t.isLeft(g))a=d===w?g:w,d=null,i._3=a;else if(i._3=d,D=!0,y=f++,c[y]=v(h,d===w?i._2:i._1,function(){return function(){delete c[y],D?D=!1:null===o?r(d,null,null):r(d,o._1,o._2)}}),D)return void(D=!1)}null===o?i=null:(i=o._1,o=o._2)}}(e,r._2._1,r._2._2)}}}return function(){var u,i,f=F,c=e,h=null,m=null;n:for(;;)switch(u=null,i=null,f){case F:switch(c.tag){case l:h&&(m=new D(d,h,m)),h=new D(l,c._1,n,n),c=c._2;break;case s:h&&(m=new D(d,h,m)),h=new D(s,n,c._2,n),c=c._1;break;case p:h&&(m=new D(d,h,m)),h=new D(p,n,c._2,n),c=c._1;break;default:i=o++,f=I,u=c,c=new D(g,i,new D(d,h,m),n),(u=B(t,r,u)).onComplete({rethrow:!1,handler:y(c)})(),a[i]=u,r&&r.register(u)}break;case I:if(null===h)break n;h._1===n?(h._1=c,f=F,c=h._2,h._2=n):(h._2=c,c=h,null===m?h=null:(h=m._1,m=m._2))}for(w=c,i=0;i<o;i++)a[i].run()}(),function(n){return new D(i,function(r){return function(){return function(n,r){var e;for(var u in m=t.left(n),c)if(c.hasOwnProperty(u))for(u in e=c[u])e.hasOwnProperty(u)&&e[u]();c=null;var o=v(n,w,r);return function(n){return new D(i,function(n){return function(){for(var n in o)o.hasOwnProperty(n)&&o[n]();return A}})}}(n,r)}})}}function R(n,t,r){return new D(i,function(e){return function(){return U(n,t,r,e)}})}return D.EMPTY=n,D.Pure=y(t),D.Throw=y(r),D.Catch=y(e),D.Sync=y(u),D.Async=y(i),D.Bind=y(o),D.Bracket=y(a),D.Fork=y(f),D.Seq=y(c),D.ParMap=y(l),D.ParApply=y(s),D.ParAlt=y(p),D.Fiber=B,D.Supervisor=function(n){var t={},r=0,e=0;return{register:function(n){var u=r++;n.onComplete({rethrow:!0,handler:function(n){return function(){e--,delete t[u]}}}),t[u]=n,e++},isEmpty:function(){return 0===e},killAll:function(i,o){return function(){if(0===e)return o();var a=0,f={};function c(r){f[r]=t[r].kill(i,function(t){return function(){delete f[r],a--,n.isLeft(t)&&n.fromLeft(t)&&setTimeout(function(){throw n.fromLeft(t)},0),0===a&&o()}})()}for(var l in t)t.hasOwnProperty(l)&&(a++,c(l));return t={},r=0,e=0,function(n){return new D(u,function(){for(var n in f)f.hasOwnProperty(n)&&f[n]()})}}}}},D.Scheduler=_,D.nonCanceler=A,D}();n._pure=t.Pure,n._map=function(n){return function(r){return r.tag===t.Pure.tag?t.Pure(n(r._1)):t.Bind(r,function(r){return t.Pure(n(r))})}},n._bind=function(n){return function(r){return t.Bind(n,r)}},n._liftEffect=t.Sync,n._parAffMap=function(n){return function(r){return t.ParMap(n,r)}},n._parAffApply=function(n){return function(r){return t.ParApply(n,r)}},n.makeAff=t.Async,n._makeFiber=function(n,r){return function(){return t.Fiber(n,null,r)}},n._sequential=t.Seq}(n["Effect.Aff"]=n["Effect.Aff"]||{}),function(n){"use strict";n["Effect.Class"]=n["Effect.Class"]||{};var t=n["Effect.Class"];t.liftEffect=function(n){return n.liftEffect},t.MonadEffect=function(n,t){this.Monad0=n,this.liftEffect=t}}(n),function(t){"use strict";(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}).unsafePartial=function(n){return n()}}(),function(t){"use strict";(n["Partial"]=n["Partial"]||{}).crashWith=function(){return function(n){throw new Error(n)}}}(),function(n){"use strict";n.Partial=n.Partial||{};var t=n.Partial,r=n.Partial;t.crashWith=r.crashWith}(n),function(n){"use strict";n["Partial.Unsafe"]=n["Partial.Unsafe"]||{};var t=n["Partial.Unsafe"],r=n["Partial.Unsafe"],e=n.Partial;t.unsafeCrashWith=function(n){return r.unsafePartial(function(t){return e.crashWith(t)(n)})}}(n),function(t){"use strict";(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}).unsafeCoerce=function(n){return n}}(),function(n){"use strict";n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{};var t=n["Unsafe.Coerce"],r=n["Unsafe.Coerce"];t.unsafeCoerce=r.unsafeCoerce}(n),function(n){"use strict";n["Effect.Aff"]=n["Effect.Aff"]||{};var t=n["Effect.Aff"],r=n["Effect.Aff"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=n["Control.Parallel"],f=n["Control.Parallel.Class"],c=n["Data.Either"],l=n["Data.Foldable"],s=n["Data.Function"],p=n["Data.Functor"],d=n["Data.Monoid"],h=n["Data.Semigroup"],m=n["Data.Unit"],w=n.Effect,v=n["Effect.Class"],g=n["Partial.Unsafe"],D=n["Unsafe.Coerce"],y=new p.Functor(r._parAffMap),A=new p.Functor(r._map),E={isLeft:function(n){if(n instanceof c.Left)return!0;if(n instanceof c.Right)return!1;throw new Error("Failed pattern match at Effect.Aff (line 390, column 12 - line 392, column 20): "+[n.constructor.name])},fromLeft:function(n){if(n instanceof c.Left)return n.value0;if(n instanceof c.Right)return g.unsafeCrashWith("unsafeFromLeft: Right");throw new Error("Failed pattern match at Effect.Aff (line 395, column 20 - line 399, column 3): "+[n.constructor.name])},fromRight:function(n){if(n instanceof c.Right)return n.value0;if(n instanceof c.Left)return g.unsafeCrashWith("unsafeFromRight: Left");throw new Error("Failed pattern match at Effect.Aff (line 400, column 21 - line 402, column 31): "+[n.constructor.name])},left:c.Left.create,right:c.Right.create},C=function(n){return function(){var t=function(n){return r._makeFiber(E,n)}(n)();return t.run(),t}},S=new u.Apply(function(){return y},r._parAffApply),_=new o.Monad(function(){return P},function(){return b}),b=new i.Bind(function(){return F},r._bind),F=new u.Apply(function(){return A},o.ap(_)),P=new e.Applicative(function(){return F},r._pure),k=new v.MonadEffect(function(){return _},r._liftEffect),M=new f.Parallel(function(){return I},function(){return _},D.unsafeCoerce,r._sequential),I=new e.Applicative(function(){return S},function(n){return f.parallel(M)(e.pure(P)(n))}),T=new h.Semigroup(function(n){return function(t){return function(r){return a.parSequence_(M)(l.foldableArray)([n(r),t(r)])}}}),B=s.const(e.pure(P)(m.unit)),U=new d.Monoid(function(){return T},B);t.launchAff=C,t.launchAff_=function(n){return p.void(w.functorEffect)(C(n))},t.nonCanceler=B,t.functorAff=A,t.applyAff=F,t.applicativeAff=P,t.bindAff=b,t.monadAff=_,t.monadEffectAff=k,t.functorParAff=y,t.applyParAff=S,t.applicativeParAff=I,t.parallelAff=M,t.semigroupCanceler=T,t.monoidCanceler=U,t.makeAff=r.makeAff}(n),function(n){"use strict";n.new=function(n){return function(){return{value:n}}},n.read=function(n){return function(){return n.value}},n.write=function(n){return function(t){return function(){return t.value=n,{}}}}}(n["Effect.Ref"]=n["Effect.Ref"]||{}),function(n){"use strict";n["Effect.Ref"]=n["Effect.Ref"]||{};var t=n["Effect.Ref"],r=n["Effect.Ref"];t.new=r.new,t.read=r.read,t.write=r.write}(n),function(n){"use strict";n["Node.Encoding"]=n["Node.Encoding"]||{};var t=n["Node.Encoding"],r=n["Data.Show"],e=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}(),i=function(){function n(){}return n.value=new n,n}(),o=function(){function n(){}return n.value=new n,n}(),a=function(){function n(){}return n.value=new n,n}(),f=function(){function n(){}return n.value=new n,n}(),c=function(){function n(){}return n.value=new n,n}(),l=function(){function n(){}return n.value=new n,n}(),s=new r.Show(function(n){if(n instanceof e)return"ASCII";if(n instanceof u)return"UTF8";if(n instanceof i)return"UTF16LE";if(n instanceof o)return"UCS2";if(n instanceof a)return"Base64";if(n instanceof f)return"Latin1";if(n instanceof c)return"Binary";if(n instanceof l)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[n.constructor.name])});t.ASCII=e,t.UTF8=u,t.UTF16LE=i,t.UCS2=o,t.Base64=a,t.Latin1=f,t.Binary=c,t.Hex=l,t.encodingToNode=function(n){if(n instanceof e)return"ascii";if(n instanceof u)return"utf8";if(n instanceof i)return"utf16le";if(n instanceof o)return"ucs2";if(n instanceof a)return"base64";if(n instanceof f)return"latin1";if(n instanceof c)return"binary";if(n instanceof l)return"hex";throw new Error("Failed pattern match at Node.Encoding (line 31, column 1 - line 31, column 37): "+[n.constructor.name])},t.showEncoding=s}(n),function(t){"use strict";(n["Node.Process"]=n["Node.Process"]||{}).process=process}(),function(n){"use strict";n["Node.Process"]=n["Node.Process"]||{};var t=n["Node.Process"],r=n["Node.Process"],e=r.process.stdout,u=r.process.stdin;t.stdin=u,t.stdout=e}(n),function(n){"use strict";n.readChunkImpl=function(n){return function(t){return function(r){if(r instanceof Buffer)return t(r);if("string"==typeof r)return n(r);throw new Error("Node.Stream.readChunkImpl: Unrecognised chunk type; expected String or Buffer, got: "+r)}}},n.onDataEitherImpl=function(n){return function(t){return function(r){return function(){t.on("data",function(t){r(n(t))()})}}}},n.onEnd=function(n){return function(t){return function(){n.on("end",t)}}},n.write=function(n){return function(t){return function(r){return function(){return n.write(t,null,r)}}}},n.writeStringImpl=function(n){return function(t){return function(r){return function(e){return function(){return n.write(r,t,e)}}}}}}(n["Node.Stream"]=n["Node.Stream"]||{}),function(n){"use strict";n.error=function(n){return new Error(n)},n.throwException=function(n){return function(){throw n}}}(n["Effect.Exception"]=n["Effect.Exception"]||{}),function(n){"use strict";n["Effect.Exception"]=n["Effect.Exception"]||{};var t=n["Effect.Exception"],r=n["Effect.Exception"];t.throw=function(n){return r.throwException(r.error(n))}}(n),function(t){"use strict";(n["Node.Buffer"]=n["Node.Buffer"]||{}).toStringImpl=function(n){return function(t){return function(){return t.toString(n)}}}}(),function(n){"use strict";n["Node.Buffer"]=n["Node.Buffer"]||{};var t=n["Node.Buffer"],r=n["Node.Buffer"],e=n["Node.Encoding"];t.toString=function(n){return r.toStringImpl(e.encodingToNode(n))}}(n),function(n){"use strict";n["Node.Stream"]=n["Node.Stream"]||{};var t=n["Node.Stream"],r=n["Node.Stream"],e=n["Control.Applicative"],u=n["Control.Bind"],i=n["Data.Either"],o=n["Data.Show"],a=n.Effect,f=n["Effect.Exception"],c=n["Node.Buffer"],l=n["Node.Encoding"],s=r.readChunkImpl(i.Left.create)(i.Right.create),p=function(n){return function(t){return r.onDataEitherImpl(s)(n)(t)}},d=function(n){return function(t){return p(n)(u.composeKleisliFlipped(a.bindEffect)(t)(function(n){if(n instanceof i.Left)return f.throw("Stream encoding should not be set");if(n instanceof i.Right)return e.pure(a.applicativeEffect)(n.value0);throw new Error("Failed pattern match at Node.Stream (line 94, column 5 - line 98, column 17): "+[n.constructor.name])}))}};t.onData=d,t.onDataString=function(n){return function(t){return function(r){return d(n)(u.composeKleisliFlipped(a.bindEffect)(r)(c.toString(t)))}}},t.onDataEither=p,t.writeString=function(n){return function(t){return r.writeStringImpl(n)(o.show(l.showEncoding)(t))}},t.onEnd=r.onEnd}(n),function(n){"use strict";n.DPA=n.DPA||{};var t=n.DPA,r=n["Control.Applicative"],e=n["Control.Bind"],u=n["Control.Category"],i=n["Control.Monad.ST.Internal"],o=n["Data.Array"],a=n["Data.Array.Partial"],f=n["Data.Array.ST"],c=n["Data.Either"],l=n["Data.Functor"],s=n["Data.Int"],p=n["Data.Maybe"],d=n["Data.Monoid"],h=n["Data.Ord"],m=n["Data.Ring"],w=n["Data.Show"],v=n["Data.String.Common"],g=n["Data.Unit"],D=n.Effect,y=n["Effect.Aff"],A=n["Effect.Class"],E=n["Effect.Ref"],C=n["Node.Encoding"],S=n["Node.Process"],_=n["Node.Stream"],b=n["Partial.Unsafe"],F=function(n){return c.either(function(n){return b.unsafeCrashWith(n)})(u.identity(u.categoryFn))((t=n,d=v.split("\n")(v.trim(t)),e.bind(c.bindEither)(c.note("n")(s.fromString(a.head()(d))))(function(n){var t,e,u=o.mapMaybe(s.fromString)((t=a.last()(d),v.split(" ")(t)));return r.pure(c.applicativeEither)(w.show(w.showInt)((e=n,function(n){return(t=function(n){return function(t){return l.map(i.functorST)(function(n){return p.fromJust()(n)})(f.peek(n)(t))}},function(){var r=f.unsafeThaw(o.replicate(e)(0))();return f.poke(0)(0)(r)(),f.poke(1)(h.abs(h.ordInt)(m.ringInt)(n[1]-n[0]|0))(r)(),i.for(2)(e)(function(e){return function(){var u=t(e-2|0)(r)(),i=t(e-1|0)(r)(),o=n[e-2|0],a=n[e-1|0],c=h.min(h.ordInt)(u+h.abs(h.ordInt)(m.ringInt)(o-n[e]|0)|0)(i+h.abs(h.ordInt)(m.ringInt)(a-n[e]|0)|0);return f.poke(e)(c)(r)(),g.unit}})(),t(e-1|0)(r)()})();var t})(u))+"\n")})));var t,d},P=y.makeAff(function(n){return function(){var t=E.new("")();return _.onDataString(S.stdin)(C.UTF8.value)(function(n){return function(){var r=E.read(t)();return E.write(r+n)(t)()}})(),_.onEnd(S.stdin)(function(){var e=E.read(t)();return n(r.pure(c.applicativeEither)(e))()})(),d.mempty(y.monoidCanceler)}}),k=y.launchAff_(e.bind(y.bindAff)(P)(function(n){return e.bind(y.bindAff)(r.pure(y.applicativeAff)(F(n)))(function(n){return A.liftEffect(y.monadEffectAff)((t=n,l.void(D.functorEffect)(_.writeString(S.stdout)(C.UTF8.value)(t)(r.pure(D.applicativeEffect)(g.unit)))));var t})}));t.main=k,t.solve=F}(n),n.DPA.main();
},{}]},{},["Focm"], null)


"use strict";

function main(input){
  const args = input.trim().split('\n').map(_=>_.split(' '));
  const n = parseInt(args[0][0],10);
  const k = parseInt(args[0][1],10);
  const h = args[1].map(_=>parseInt(_,10));

  const dp = Array(n).fill(0); // i => i-stepでの最小コスト
  for(let i=1; i<n; i++){
    let minCost = dp[i-1] + Math.abs(h[i] - h[i-1]);
    for(let j=2; j<=k; j++){
      if(i-j < 0) break;
      const cost = dp[i-j] + Math.abs(h[i] - h[i-j]);
      minCost = Math.min(minCost, cost);
    }
    dp[i] = minCost;
  }

  console.log(dp[n-1]);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));

Score : 100 points

Problem Statement

There are N stones, numbered 1, 2, \ldots, N.
For each i (1 \leq i \leq N), the height of Stone i is h_i.

There is a frog who is initially on Stone 1.
He will repeat the following action some number of times to reach Stone N:

If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ldots, i + K. Here, a cost of |h_i - h_j| is incurred, where j is the stone to land on.

Find the minimum possible total cost incurred before the frog reaches Stone N.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

If we follow the path 1 → 2 → 5, the total cost incurred would be |10 - 30| + |30 - 20| = 30.

Sample Input 2

3 1
10 20 10

Sample Output 2

20

If we follow the path 1 → 2 → 3, the total cost incurred would be |10 - 20| + |20 - 10| = 20.

Sample Input 3

2 100
10 10

Sample Output 3

0

If we follow the path 1 → 2, the total cost incurred would be |10 - 10| = 0.

Sample Input 4

10 4
40 10 20 70 80 10 20 70 80 60

Sample Output 4

40

If we follow the path 1 → 4 → 8 → 10, the total cost incurred would be |40 - 70| + |70 - 70| + |70 - 60| = 40.


'use strict'
function main(input) {
  let tmp = input.split('\n');
  let k = tmp[0].split(' ')[1];
  let stones = tmp[1].split(' ').map(element => parseInt(element, 10));

  let dp = Array(stones.length).fill(Infinity);
  dp[0] = 0;
  for (let i = 0; i < stones.length; i++) {
    for(let j = i + 1; j <= i + k; j++) {
      if (j < stones.length) {
      	dp[j] = Math.min(dp[j, dp[i] + Math.abs(stones[i] - stones[j]))
       }
    }
  }
   console.log(dp[stones.length - 1])
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
  //パラメータ受け取り
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  var H_arr = inputStr.map( inputStr => parseInt(inputStr));

  //解法としてDPを用いる
  var i = 0;	//今たっている場所
  var ans = []; //回答格納用配列
  //ansの配列要素Nの確定と初期化
  for(var i=0 ; i<N ; i++){
    ans.push(0);
  }

  //階段の0段目のコストをメモ。値は0
  ans[0] = 0;
  //階段の1段目に進んだ時のコストをメモ
  ans[1] = Math.abs(H_arr[1]-H_arr[0]);
  //階段の3段目以降のコストをforループで処理
  for( var i=2 ; i<N ; i++){
    var last = 10000000;
    for(var j=1 ; j<=K ; j++){
      if( i >= j){
        //自分のところ(i段目)にj段前から来た場合の値を格納
        var tmp = ans[i-j]+Math.abs(H_arr[i]-H_arr[i-j]);
        last = Math.min(tmp,last);
      }
    }
    //より小さい値(最小コスト)を回答配列の自分の段に格納
    ans[i] = last;
  }
  //結果表示
  console.log(ans[N-1]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
  //パラメータ受け取り
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  var H_arr = inputStr.map( inputStr => parseInt(inputStr));

  //解法としてDPを用いる
  var i = 0;	//今たっている場所
  var ans = []; //回答格納用配列
  //ansの配列要素Nの確定と初期化
  for(var i=0 ; i<N ; i++){
    ans.push(0);
  }

  //階段の0段目のコストをメモ。値は0
  ans[0] = 0;
  //階段の1段目に進んだ時のコストをメモ
  ans[1] = Math.abs(H_arr[1]-H_arr[0]);
  //階段の3段目以降のコストをforループで処理
  for( var i=2 ; i<N ; i++){
    var last = 1000000;
    for(var j=1 ; j<=K ; j++){
      if( i >= j){
        //自分のところ(i段目)にj段前から来た場合の値を格納
        var tmp = ans[i-j]+Math.abs(H_arr[i]-H_arr[i-j]);
        last = Math.min(tmp,last);
      }
    }
    //より小さい値(最小コスト)を回答配列の自分の段に格納
    ans[i] = last;
  }
  //結果表示
  console.log(ans[N-1]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
  //パラメータ受け取り
  input = input.split("\n");
  inputStr = input[0].split(" ");
  var N = Number.parseInt(inputStr[0]);
  var K = Number.parseInt(inputStr[1]);
  inputStr = input[1].split(" ");
  var H_arr = inputStr.map( inputStr => parseInt(inputStr));

  //解法として貪欲法を用いる
  var i = 0;	//今たっている場所
  var ans = []; //回答格納用配列
  //階段の0段目のコストをメモ。値は0
  ans.push(0);
  //階段の1段目に進んだ時のコストをメモ
  //ans.push(Math.abs(H_arr[1]-H_arr[0]));
  //階段の3段目以降のコストをforループで処理
  for( var i=1 ; i<N ; i++){
    var last = 99999;
    for(var j=1 ; j<=K ; j++){
      if(i-j<0){ break; }
      //自分のところ(i段目)に1段前から来た場合の値を格納
      var tmp = ans[i-j]+Math.abs(H_arr[i]-H_arr[i-j]);
      last = Math.min(tmp,last);
      //console.log(H_arr[i],H_arr[i-j]);
    }
    //より小さい値(最小コスト)を回答配列の自分の段に格納
    ans.push(last);
    //console.log(ans);
  }
  //結果表示
  console.log(ans[ans.length -1]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


module.exports=function(r){var e={};function t(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return r[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}return t.m=r,t.c=e,t.d=function(r,e,n){t.o(r,e)||Object.defineProperty(r,e,{enumerable:!0,get:n})},t.r=function(r){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(r,"__esModule",{value:!0})},t.t=function(r,e){if(1&e&&(r=t(r)),8&e)return r;if(4&e&&"object"==typeof r&&r&&r.__esModule)return r;var n=Object.create(null);if(t.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:r}),2&e&&"string"!=typeof r)for(var o in r)t.d(n,o,function(e){return r[e]}.bind(null,o));return n},t.n=function(r){var e=r&&r.__esModule?function(){return r.default}:function(){return r};return t.d(e,"a",e),e},t.o=function(r,e){return Object.prototype.hasOwnProperty.call(r,e)},t.p="",t(t.s=0)}([function(r,e,t){t(1)(t(2).readFileSync("/dev/stdin","UTF-8"))},function(r,e){function t(r,e){return function(r){if(Array.isArray(r))return r}(r)||function(r,e){var t=[],n=!0,o=!1,u=void 0;try{for(var i,f=r[Symbol.iterator]();!(n=(i=f.next()).done)&&(t.push(i.value),!e||t.length!==e);n=!0);}catch(r){o=!0,u=r}finally{try{n||null==f.return||f.return()}finally{if(o)throw u}}return t}(r,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}r.exports=function(r){var e=r.split("\n"),n=t(e[0].split(" ").map(function(r){return Number(r)}),2),o=n[0],u=n[1],i=e[1].split(" ").map(function(r){return Number(r)}),f=new Array(o).fill(2e10);f[0]=0;for(var l=0;l<o;l++)for(var a=1;a<=u&&!(l+a>=o);a++){var c=f[l]+Math.abs(i[l+a]-i[l]);c<f[l+a]&&(f[l+a]=c)}var p=f[o-1];console.log(p)}},function(r,e){r.exports=require("fs")}]);


'use strict'
function main(input) {
  const tmp = input.split('\n');
  const NK = tmp[0].split(' ').map((elem) => parseInt(elem, 10));
  const N = NK[0];
  const K = NK[1];
  const h = tmp[1].split(' ').map((elem) => parseInt(elem, 10));

  let dp = new Array(N);
  dp.fill(Infinity);
  dp[0] = 0;
  for (let i = 1; i < N; i++) {
    for (let k = 1; k <= K; k++) {
      if (i >= k) {
        dp[i] = Math.min(dp[i], dp[i - k] + Math.abs(h[i] - h[i - k]));
      }
    }
  }

  console.log(dp[N - 1]);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"Focm":[function(require,module,exports) {
var n={};!function(t){"use strict";(n["Control.Apply"]=n["Control.Apply"]||{}).arrayApply=function(n){return function(t){for(var r=n.length,e=t.length,u=new Array(r*e),i=0,o=0;o<r;o++)for(var a=n[o],f=0;f<e;f++)u[i++]=a(t[f]);return u}}}(),function(n){"use strict";n["Control.Semigroupoid"]=n["Control.Semigroupoid"]||{};var t=n["Control.Semigroupoid"],r=function(n){this.compose=n},e=new r(function(n){return function(t){return function(r){return n(t(r))}}});t.compose=function(n){return n.compose},t.Semigroupoid=r,t.semigroupoidFn=e}(n),function(n){"use strict";n["Control.Category"]=n["Control.Category"]||{};var t=n["Control.Category"],r=n["Control.Semigroupoid"],e=function(n,t){this.Semigroupoid0=n,this.identity=t},u=new e(function(){return r.semigroupoidFn},function(n){return n});t.Category=e,t.identity=function(n){return n.identity},t.categoryFn=u}(n),function(n){"use strict";n["Data.Function"]=n["Data.Function"]||{};var t=n["Data.Function"];t.flip=function(n){return function(t){return function(r){return n(r)(t)}}},t.const=function(n){return function(t){return n}}}(n),function(t){"use strict";(n["Data.Functor"]=n["Data.Functor"]||{}).arrayMap=function(n){return function(t){for(var r=t.length,e=new Array(r),u=0;u<r;u++)e[u]=n(t[u]);return e}}}(),function(t){"use strict";(n["Data.Unit"]=n["Data.Unit"]||{}).unit={}}(),function(n){"use strict";n["Data.Unit"]=n["Data.Unit"]||{};var t=n["Data.Unit"],r=n["Data.Unit"];t.unit=r.unit}(n),function(n){"use strict";n["Data.Functor"]=n["Data.Functor"]||{};var t=n["Data.Functor"],r=n["Data.Functor"],e=n["Data.Function"],u=n["Data.Unit"],i=function(n){this.map=n},o=function(n){return n.map},a=new i(r.arrayMap);t.Functor=i,t.map=o,t.void=function(n){return o(n)(e.const(u.unit))},t.functorArray=a}(n),function(n){"use strict";n["Control.Apply"]=n["Control.Apply"]||{};var t=n["Control.Apply"],r=n["Control.Apply"],e=n["Control.Category"],u=n["Data.Function"],i=n["Data.Functor"],o=function(n,t){this.Functor0=n,this.apply=t},a=new o(function(){return i.functorArray},r.arrayApply),f=function(n){return n.apply};t.Apply=o,t.apply=f,t.applySecond=function(n){return function(t){return function(r){return f(n)(i.map(n.Functor0())(u.const(e.identity(e.categoryFn)))(t))(r)}}},t.applyArray=a}(n),function(n){"use strict";n["Control.Applicative"]=n["Control.Applicative"]||{};var t=n["Control.Applicative"],r=n["Control.Apply"],e=n["Data.Unit"],u=function(n){return n.pure};t.Applicative=function(n,t){this.Apply0=n,this.pure=t},t.pure=u,t.liftA1=function(n){return function(t){return function(e){return r.apply(n.Apply0())(u(n)(t))(e)}}},t.when=function(n){return function(t){return function(r){if(t)return r;if(!t)return u(n)(e.unit);throw new Error("Failed pattern match at Control.Applicative (line 57, column 1 - line 57, column 63): "+[t.constructor.name,r.constructor.name])}}}}(n),function(t){"use strict";(n["Control.Bind"]=n["Control.Bind"]||{}).arrayBind=function(n){return function(t){for(var r=[],e=0,u=n.length;e<u;e++)Array.prototype.push.apply(r,t(n[e]));return r}}}(),function(n){"use strict";n["Control.Bind"]=n["Control.Bind"]||{};var t=n["Control.Bind"],r=n["Control.Bind"],e=n["Control.Apply"],u=n["Data.Function"],i=function(n,t){this.Apply0=n,this.bind=t},o=new i(function(){return e.applyArray},r.arrayBind),a=function(n){return n.bind},f=function(n){return u.flip(a(n))};t.Bind=i,t.bind=a,t.bindFlipped=f,t.composeKleisliFlipped=function(n){return function(t){return function(r){return function(e){return f(n)(t)(r(e))}}}},t.bindArray=o}(n),function(n){"use strict";n["Control.Monad"]=n["Control.Monad"]||{};var t=n["Control.Monad"],r=n["Control.Applicative"],e=n["Control.Bind"];t.Monad=function(n,t){this.Applicative0=n,this.Bind1=t},t.ap=function(n){return function(t){return function(u){return e.bind(n.Bind1())(t)(function(t){return e.bind(n.Bind1())(u)(function(e){return r.pure(n.Applicative0())(t(e))})})}}}}(n),function(n){"use strict";n.map_=function(n){return function(t){return function(){return n(t())}}},n.pure_=function(n){return function(){return n}},n.bind_=function(n){return function(t){return function(){return t(n())()}}},n.for=function(n){return function(t){return function(r){return function(){for(var e=n;e<t;e++)r(e)()}}}}}(n["Control.Monad.ST.Internal"]=n["Control.Monad.ST.Internal"]||{}),function(n){"use strict";n["Control.Monad.ST.Internal"]=n["Control.Monad.ST.Internal"]||{};var t=n["Control.Monad.ST.Internal"],r=n["Control.Monad.ST.Internal"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=new n["Data.Functor"].Functor(r.map_),f=new o.Monad(function(){return s},function(){return c}),c=new i.Bind(function(){return l},r.bind_),l=new u.Apply(function(){return a},o.ap(f)),s=new e.Applicative(function(){return l},r.pure_);t.functorST=a,t.applyST=l,t.applicativeST=s,t.bindST=c,t.monadST=f,t.for=r.for}(n),function(n){"use strict";n["Control.Parallel.Class"]=n["Control.Parallel.Class"]||{};var t=n["Control.Parallel.Class"];t.parallel=function(n){return n.parallel},t.sequential=function(n){return n.sequential},t.Parallel=function(n,t,r,e){this.Applicative1=n,this.Monad0=t,this.parallel=r,this.sequential=e}}(n),function(n){"use strict";n.foldrArray=function(n){return function(t){return function(r){for(var e=t,u=r.length-1;u>=0;u--)e=n(r[u])(e);return e}}},n.foldlArray=function(n){return function(t){return function(r){for(var e=t,u=r.length,i=0;i<u;i++)e=n(e)(r[i]);return e}}}}(n["Data.Foldable"]=n["Data.Foldable"]||{}),function(n){"use strict";n["Data.Monoid"]=n["Data.Monoid"]||{};var t=n["Data.Monoid"];t.Monoid=function(n,t){this.Semigroup0=n,this.mempty=t},t.mempty=function(n){return n.mempty}}(n),function(n){"use strict";n["Data.Semigroup"]=n["Data.Semigroup"]||{};var t=n["Data.Semigroup"];t.Semigroup=function(n){this.append=n},t.append=function(n){return n.append}}(n),function(n){"use strict";n["Data.Foldable"]=n["Data.Foldable"]||{};var t=n["Data.Foldable"],r=n["Data.Foldable"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Data.Monoid"],o=n["Data.Semigroup"],a=n["Data.Unit"],f=function(n,t,r){this.foldMap=n,this.foldl=t,this.foldr=r},c=function(n){return n.foldr},l=function(n){return function(t){return function(r){return c(n)(function(n){return function(e){return o.append(t.Semigroup0())(r(n))(e)}})(i.mempty(t))}}},s=new f(function(n){return l(s)(n)},r.foldlArray,r.foldrArray);t.Foldable=f,t.foldr=c,t.foldl=function(n){return n.foldl},t.foldMap=function(n){return n.foldMap},t.foldMapDefaultR=l,t.traverse_=function(n){return function(t){return function(r){return c(t)(function(t){return u.applySecond(n.Apply0())(r(t))})(e.pure(n)(a.unit))}}},t.foldableArray=s}(n),function(n){"use strict";n["Control.Parallel"]=n["Control.Parallel"]||{};var t=n["Control.Parallel"],r=n["Control.Category"],e=n["Control.Parallel.Class"],u=n["Data.Foldable"],i=function(n){return function(t){return function(r){return function(i){return e.sequential(n)(u.traverse_(n.Applicative1())(t)(function(t){return e.parallel(n)(r(t))})(i))}}}};t.parTraverse_=i,t.parSequence_=function(n){return function(t){return i(n)(t)(r.identity(r.categoryFn))}}}(n),function(n){"use strict";n.replicate="function"==typeof Array.prototype.fill?function(n){return function(t){return n<1?[]:new Array(n).fill(t)}}:function(n){return function(t){for(var r=[],e=0,u=0;u<n;u++)r[e++]=t;return r}},n.length=function(n){return n.length}}(n["Data.Array"]=n["Data.Array"]||{}),function(n){"use strict";n["Data.Maybe"]=n["Data.Maybe"]||{};var t=n["Data.Maybe"],r=function(){function n(){}return n.value=new n,n}(),e=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}();t.Nothing=r,t.Just=e,t.maybe=function(n){return function(t){return function(u){if(u instanceof r)return n;if(u instanceof e)return t(u.value0);throw new Error("Failed pattern match at Data.Maybe (line 217, column 1 - line 217, column 51): "+[n.constructor.name,t.constructor.name,u.constructor.name])}}},t.fromJust=function(n){return function(n){if(n instanceof e)return n.value0;throw new Error("Failed pattern match at Data.Maybe (line 268, column 1 - line 268, column 46): "+[n.constructor.name])}}}(n),function(n){"use strict";n["Data.Array"]=n["Data.Array"]||{};var t=n["Data.Array"],r=n["Data.Array"],e=n["Control.Bind"],u=n["Data.Function"],i=n["Data.Maybe"],o=function(n){return[n]},a=u.flip(e.bind(e.bindArray));t.singleton=o,t.concatMap=a,t.mapMaybe=function(n){return a(function(t){return i.maybe([])(o)(n(t))})},t.replicate=r.replicate,t.length=r.length}(n),function(n){"use strict";n["Data.Array.Partial"]=n["Data.Array.Partial"]||{};var t=n["Data.Array.Partial"],r=n["Data.Array"];t.head=function(n){return function(n){return n[0]}},t.last=function(n){return function(n){return n[r.length(n)-1|0]}}}(n),function(n){"use strict";n.peekImpl=function(n){return function(t){return function(r){return function(e){return function(){return r>=0&&r<e.length?n(e[r]):t}}}}},n.poke=function(n){return function(t){return function(r){return function(){var e=n>=0&&n<r.length;return e&&(r[n]=t),e}}}}}(n["Data.Array.ST"]=n["Data.Array.ST"]||{}),function(n){"use strict";n["Data.Array.ST"]=n["Data.Array.ST"]||{};var t=n["Data.Array.ST"],r=n["Data.Array.ST"],e=n["Control.Applicative"],u=n["Control.Monad.ST.Internal"],i=n["Data.Maybe"],o=r.peekImpl(i.Just.create)(i.Nothing.value);t.peek=o,t.unsafeThaw=function(n){return e.pure(u.applicativeST)(n)},t.poke=r.poke}(n),function(n){"use strict";n.topInt=2147483647,n.bottomInt=-2147483648}(n["Data.Bounded"]=n["Data.Bounded"]||{}),function(t){"use strict";(n["Data.Eq"]=n["Data.Eq"]||{}).refEq=function(n){return function(t){return n===t}}}(),function(n){"use strict";n["Data.Eq"]=n["Data.Eq"]||{};var t=n["Data.Eq"],r=function(n){this.eq=n},e=new r(n["Data.Eq"].refEq);t.Eq=r,t.eq=function(n){return n.eq},t.eqInt=e}(n),function(t){"use strict";(n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{}).unsafeCompareImpl=function(n){return function(t){return function(r){return function(e){return function(u){return e<u?n:e===u?t:r}}}}}}(),function(n){"use strict";n["Data.Ordering"]=n["Data.Ordering"]||{};var t=n["Data.Ordering"],r=function(){function n(){}return n.value=new n,n}(),e=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}();t.LT=r,t.GT=e,t.EQ=u}(n),function(n){"use strict";n["Data.Ord.Unsafe"]=n["Data.Ord.Unsafe"]||{};var t=n["Data.Ord.Unsafe"],r=n["Data.Ord.Unsafe"],e=n["Data.Ordering"],u=r.unsafeCompareImpl(e.LT.value)(e.EQ.value)(e.GT.value);t.unsafeCompare=u}(n),function(t){"use strict";(n["Data.Ring"]=n["Data.Ring"]||{}).intSub=function(n){return function(t){return n-t|0}}}(),function(n){"use strict";n.intAdd=function(n){return function(t){return n+t|0}},n.intMul=function(n){return function(t){return n*t|0}}}(n["Data.Semiring"]=n["Data.Semiring"]||{}),function(n){"use strict";n["Data.Semiring"]=n["Data.Semiring"]||{};var t=n["Data.Semiring"],r=n["Data.Semiring"],e=function(n,t,r,e){this.add=n,this.mul=t,this.one=r,this.zero=e},u=new e(r.intAdd,r.intMul,1,0);t.Semiring=e,t.add=function(n){return n.add},t.zero=function(n){return n.zero},t.mul=function(n){return n.mul},t.one=function(n){return n.one},t.semiringInt=u}(n),function(n){"use strict";n["Data.Ring"]=n["Data.Ring"]||{};var t=n["Data.Ring"],r=n["Data.Ring"],e=n["Data.Semiring"],u=function(n,t){this.Semiring0=n,this.sub=t},i=function(n){return n.sub},o=new u(function(){return e.semiringInt},r.intSub);t.Ring=u,t.sub=i,t.negate=function(n){return function(t){return i(n)(e.zero(n.Semiring0()))(t)}},t.ringInt=o}(n),function(n){"use strict";n["Data.Ord"]=n["Data.Ord"]||{};var t=n["Data.Ord"],r=n["Data.Eq"],e=n["Data.Ord.Unsafe"],u=n["Data.Ordering"],i=n["Data.Ring"],o=n["Data.Semiring"],a=function(n,t){this.Eq0=n,this.compare=t},f=new a(function(){return r.eqInt},e.unsafeCompare),c=function(n){return n.compare},l=function(n){return function(t){return function(r){return!(c(n)(t)(r)instanceof u.LT)}}};t.Ord=a,t.compare=c,t.greaterThanOrEq=l,t.min=function(n){return function(t){return function(r){var e=c(n)(t)(r);if(e instanceof u.LT)return t;if(e instanceof u.EQ)return t;if(e instanceof u.GT)return r;throw new Error("Failed pattern match at Data.Ord (line 119, column 3 - line 122, column 12): "+[e.constructor.name])}}},t.abs=function(n){return function(t){return function(r){return l(n)(r)(o.zero(t.Semiring0()))?r:i.negate(t)(r)}}},t.ordInt=f}(n),function(n){"use strict";n["Data.Bounded"]=n["Data.Bounded"]||{};var t=n["Data.Bounded"],r=n["Data.Bounded"],e=n["Data.Ord"],u=function(n,t,r){this.Ord0=n,this.bottom=t,this.top=r},i=new u(function(){return e.ordInt},r.bottomInt,r.topInt);t.Bounded=u,t.bottom=function(n){return n.bottom},t.top=function(n){return n.top},t.boundedInt=i}(n),function(n){"use strict";n["Data.Either"]=n["Data.Either"]||{};var t=n["Data.Either"],r=n["Control.Applicative"],e=n["Control.Apply"],u=n["Control.Bind"],i=n["Data.Functor"],o=n["Data.Maybe"],a=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),f=function(){function n(n){this.value0=n}return n.create=function(t){return new n(t)},n}(),c=new i.Functor(function(n){return function(t){if(t instanceof a)return new a(t.value0);if(t instanceof f)return new f(n(t.value0));throw new Error("Failed pattern match at Data.Either (line 38, column 8 - line 38, column 52): "+[t.constructor.name])}}),l=function(n){return function(t){return function(r){if(r instanceof a)return n(r.value0);if(r instanceof f)return t(r.value0);throw new Error("Failed pattern match at Data.Either (line 238, column 1 - line 238, column 64): "+[n.constructor.name,t.constructor.name,r.constructor.name])}}},s=new e.Apply(function(){return c},function(n){return function(t){if(n instanceof a)return new a(n.value0);if(n instanceof f)return i.map(c)(n.value0)(t);throw new Error("Failed pattern match at Data.Either (line 82, column 1 - line 82, column 41): "+[n.constructor.name,t.constructor.name])}}),p=new u.Bind(function(){return s},l(function(n){return function(t){return new a(n)}})(function(n){return function(t){return t(n)}})),d=new r.Applicative(function(){return s},f.create);t.Left=a,t.Right=f,t.either=l,t.note=function(n){return o.maybe(new a(n))(f.create)},t.functorEither=c,t.applyEither=s,t.applicativeEither=d,t.bindEither=p}(n),function(t){"use strict";(n["Data.Int"]=n["Data.Int"]||{}).fromStringAsImpl=function(n){return function(t){return function(r){var e;e=r<11?"[0-"+(r-1).toString()+"]":11===r?"[0-9a]":"[0-9a-"+String.fromCharCode(86+r)+"]";var u=new RegExp("^[\\+\\-]?"+e+"+$","i");return function(e){if(u.test(e)){var i=parseInt(e,r);return(0|i)===i?n(i):t}return t}}}}}(),function(n){"use strict";n["Data.Int"]=n["Data.Int"]||{};var t=n["Data.Int"],r=n["Data.Int"],e=n["Data.Maybe"],u=r.fromStringAsImpl(e.Just.create)(e.Nothing.value),i=u(10);t.fromString=i,t.fromStringAs=u}(n),function(t){"use strict";(n["Data.Show"]=n["Data.Show"]||{}).showIntImpl=function(n){return n.toString()}}(),function(n){"use strict";n["Data.Show"]=n["Data.Show"]||{};var t=n["Data.Show"],r=function(n){this.show=n},e=new r(n["Data.Show"].showIntImpl);t.Show=r,t.show=function(n){return n.show},t.showInt=e}(n),function(n){"use strict";n.split=function(n){return function(t){return t.split(n)}},n.trim=function(n){return n.trim()}}(n["Data.String.Common"]=n["Data.String.Common"]||{}),function(n){"use strict";n["Data.String.Common"]=n["Data.String.Common"]||{};var t=n["Data.String.Common"],r=n["Data.String.Common"];t.split=r.split,t.trim=r.trim}(n),function(n){"use strict";n["Data.Tuple"]=n["Data.Tuple"]||{};var t=n["Data.Tuple"],r=function(){function n(n,t){this.value0=n,this.value1=t}return n.create=function(t){return function(r){return new n(t,r)}},n}();t.Tuple=r}(n),function(n){"use strict";n.pureE=function(n){return function(){return n}},n.bindE=function(n){return function(t){return function(){return t(n())()}}}}(n.Effect=n.Effect||{}),function(n){"use strict";n.Effect=n.Effect||{};var t=n.Effect,r=n.Effect,e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=n["Data.Functor"],f=new o.Monad(function(){return s},function(){return c}),c=new i.Bind(function(){return l},r.bindE),l=new u.Apply(function(){return p},o.ap(f)),s=new e.Applicative(function(){return l},r.pureE),p=new a.Functor(e.liftA1(s));t.functorEffect=p,t.applyEffect=l,t.applicativeEffect=s,t.bindEffect=c,t.monadEffect=f}(n),function(n){"use strict";var t=function(){var n={},t="Pure",r="Throw",e="Catch",u="Sync",i="Async",o="Bind",a="Bracket",f="Fork",c="Sequential",l="Map",s="Apply",p="Alt",d="Cons",h="Resume",m="Release",w="Finalizer",v="Finalized",D="Forked";function g(n,t,r,e){this.tag=n,this._1=t,this._2=r,this._3=e}function y(n){var t=function(t,r,e){return new g(n,t,r,e)};return t.tag=n,t}function E(n){return new g(t,void 0)}function A(n){try{n()}catch(t){setTimeout(function(){throw t},0)}}function C(n,t,r){try{return t(r())}catch(e){return n(e)}}function S(n,t,r){try{return t(r)()}catch(e){return r(n(e))(),E}}var _=function(){var n=1024,t=0,r=0,e=new Array(n),u=!1;function i(){var i;for(u=!0;0!==t;)t--,i=e[r],e[r]=void 0,r=(r+1)%n,i();u=!1}return{isDraining:function(){return u},enqueue:function(o){var a;t===n&&(a=u,i(),u=a),e[(r+t)%n]=o,t++,u||i()}}}();var b=0,F=1,P=2,k=3,M=4,I=5,B=6;function T(n,l,s){var p=0,D=b,y=s,E=null,U=null,R=null,L=null,q=null,O=0,x=0,W=null,z=!0;function J(s){for(var x,G,K;;)switch(x=null,G=null,K=null,D){case P:D=F,y=R(y),null===L?R=null:(R=L._1,L=L._2);break;case k:n.isLeft(y)?(D=I,E=y,y=null):null===R?D=I:(D=P,y=n.fromRight(y));break;case F:switch(y.tag){case o:R&&(L=new g(d,R,L)),R=y._2,D=F,y=y._1;break;case t:null===R?(D=I,y=n.right(y._1)):(D=P,y=y._1);break;case u:D=k,y=C(n.left,n.right,y._1);break;case i:return D=M,void(y=S(n.left,y._1,function(n){return function(){p===s&&(p++,_.enqueue(function(){p===s+1&&(D=k,y=n,J(p))}))}}));case r:D=I,E=n.left(y._1),y=null;break;case e:q=new g(d,y,null===R?q:new g(d,new g(h,R,L),q,U),U),R=null,L=null,D=F,y=y._1;break;case a:O++,q=new g(d,y,null===R?q:new g(d,new g(h,R,L),q,U),U),R=null,L=null,D=F,y=y._1;break;case f:D=k,x=T(n,l,y._2),l&&l.register(x),y._1&&x.run(),y=n.right(x);break;case c:D=F,y=N(n,l,y._1)}break;case I:if(R=null,L=null,null===q)D=B,y=U||E||y;else switch(x=q._3,K=q._1,q=q._2,K.tag){case e:U&&U!==x&&0===O?D=I:E&&(D=F,y=K._2(n.fromLeft(E)),E=null);break;case h:U&&U!==x&&0===O||E?D=I:(R=K._1,L=K._2,D=P,y=n.fromRight(y));break;case a:O--,null===E&&(G=n.fromRight(y),q=new g(d,new g(m,K._2,G),q,x),(U===x||O>0)&&(D=F,y=K._3(G)));break;case m:q=new g(d,new g(v,y,E),q,U),D=F,y=U&&U!==x&&0===O?K._1.killed(n.fromLeft(U))(K._2):E?K._1.failed(n.fromLeft(E))(K._2):K._1.completed(n.fromRight(y))(K._2),E=null,O++;break;case w:O++,q=new g(d,new g(v,y,E),q,U),D=F,y=K._1;break;case v:O--,D=I,y=K._1,E=K._2}break;case B:for(var Q in W)W.hasOwnProperty(Q)&&(z=z&&W[Q].rethrow,A(W[Q].handler(y)));return W=null,void(U&&E?setTimeout(function(){throw n.fromLeft(E)},0):n.isLeft(y)&&z&&setTimeout(function(){if(z)throw n.fromLeft(y)},0));case b:D=F;break;case M:return}}function G(n){return function(){if(D===B)return z=z&&n.rethrow,n.handler(y)(),function(){};var t=x++;return(W=W||{})[t]=n,function(){null!==W&&delete W[t]}}}return{kill:function(t,r){return function(){if(D===B)return r(n.right(void 0))(),function(){};var e=G({rethrow:!1,handler:function(){return r(n.right(void 0))}})();switch(D){case b:U=n.left(t),D=B,y=U,J(p);break;case M:null===U&&(U=n.left(t)),0===O&&(D===M&&(q=new g(d,new g(w,y(t)),q,U)),D=I,y=null,E=null,J(++p));break;default:null===U&&(U=n.left(t)),0===O&&(D=I,y=null,E=null)}return e}},join:function(n){return function(){var t=G({rethrow:!1,handler:n})();return D===b&&J(p),t}},onComplete:G,isSuspended:function(){return D===b},run:function(){D===b&&(_.isDraining()?J(p):_.enqueue(function(){J(p)}))}}}function U(t,r,e,u){var o=0,a={},f=0,c={},h=new Error("[ParAff] Early exit"),m=null,w=n;function v(r,e,u){var i,o,f=e,c=null,h=null,m=0,w={};n:for(;;)switch(i=null,f.tag){case D:if(f._3===n&&(i=a[f._1],w[m++]=i.kill(r,function(n){return function(){0===--m&&u(n)()}})),null===c)break n;f=c._2,null===h?c=null:(c=h._1,h=h._2);break;case l:f=f._2;break;case s:case p:c&&(h=new g(d,c,h)),c=f,f=f._1}if(0===m)u(t.right(void 0))();else for(o=0,i=m;o<i;o++)w[o]=w[o]();return w}function y(r){return function(e){return function(){delete a[r._1],r._3=e,function r(e,i,o){var a,d,w,D,g,y;for(t.isLeft(e)?(a=e,d=null):(d=e,a=null);;){if(w=null,D=null,g=null,y=null,null!==m)return;if(null===i)return void u(a||d)();if(i._3!==n)return;switch(i.tag){case l:null===a?(i._3=t.right(i._1(t.fromRight(d))),d=i._3):i._3=a;break;case s:if(w=i._1._3,D=i._2._3,a){if(i._3=a,g=!0,y=f++,c[y]=v(h,a===w?i._2:i._1,function(){return function(){delete c[y],g?g=!1:null===o?r(a,null,null):r(a,o._1,o._2)}}),g)return void(g=!1)}else{if(w===n||D===n)return;d=t.right(t.fromRight(w)(t.fromRight(D))),i._3=d}break;case p:if(w=i._1._3,D=i._2._3,w===n&&t.isLeft(D)||D===n&&t.isLeft(w))return;if(w!==n&&t.isLeft(w)&&D!==n&&t.isLeft(D))a=d===w?D:w,d=null,i._3=a;else if(i._3=d,g=!0,y=f++,c[y]=v(h,d===w?i._2:i._1,function(){return function(){delete c[y],g?g=!1:null===o?r(d,null,null):r(d,o._1,o._2)}}),g)return void(g=!1)}null===o?i=null:(i=o._1,o=o._2)}}(e,r._2._1,r._2._2)}}}return function(){var u,i,f=F,c=e,h=null,m=null;n:for(;;)switch(u=null,i=null,f){case F:switch(c.tag){case l:h&&(m=new g(d,h,m)),h=new g(l,c._1,n,n),c=c._2;break;case s:h&&(m=new g(d,h,m)),h=new g(s,n,c._2,n),c=c._1;break;case p:h&&(m=new g(d,h,m)),h=new g(p,n,c._2,n),c=c._1;break;default:i=o++,f=I,u=c,c=new g(D,i,new g(d,h,m),n),(u=T(t,r,u)).onComplete({rethrow:!1,handler:y(c)})(),a[i]=u,r&&r.register(u)}break;case I:if(null===h)break n;h._1===n?(h._1=c,f=F,c=h._2,h._2=n):(h._2=c,c=h,null===m?h=null:(h=m._1,m=m._2))}for(w=c,i=0;i<o;i++)a[i].run()}(),function(n){return new g(i,function(r){return function(){return function(n,r){var e;for(var u in m=t.left(n),c)if(c.hasOwnProperty(u))for(u in e=c[u])e.hasOwnProperty(u)&&e[u]();c=null;var o=v(n,w,r);return function(n){return new g(i,function(n){return function(){for(var n in o)o.hasOwnProperty(n)&&o[n]();return E}})}}(n,r)}})}}function N(n,t,r){return new g(i,function(e){return function(){return U(n,t,r,e)}})}return g.EMPTY=n,g.Pure=y(t),g.Throw=y(r),g.Catch=y(e),g.Sync=y(u),g.Async=y(i),g.Bind=y(o),g.Bracket=y(a),g.Fork=y(f),g.Seq=y(c),g.ParMap=y(l),g.ParApply=y(s),g.ParAlt=y(p),g.Fiber=T,g.Supervisor=function(n){var t={},r=0,e=0;return{register:function(n){var u=r++;n.onComplete({rethrow:!0,handler:function(n){return function(){e--,delete t[u]}}}),t[u]=n,e++},isEmpty:function(){return 0===e},killAll:function(i,o){return function(){if(0===e)return o();var a=0,f={};function c(r){f[r]=t[r].kill(i,function(t){return function(){delete f[r],a--,n.isLeft(t)&&n.fromLeft(t)&&setTimeout(function(){throw n.fromLeft(t)},0),0===a&&o()}})()}for(var l in t)t.hasOwnProperty(l)&&(a++,c(l));return t={},r=0,e=0,function(n){return new g(u,function(){for(var n in f)f.hasOwnProperty(n)&&f[n]()})}}}}},g.Scheduler=_,g.nonCanceler=E,g}();n._pure=t.Pure,n._map=function(n){return function(r){return r.tag===t.Pure.tag?t.Pure(n(r._1)):t.Bind(r,function(r){return t.Pure(n(r))})}},n._bind=function(n){return function(r){return t.Bind(n,r)}},n._liftEffect=t.Sync,n._parAffMap=function(n){return function(r){return t.ParMap(n,r)}},n._parAffApply=function(n){return function(r){return t.ParApply(n,r)}},n.makeAff=t.Async,n._makeFiber=function(n,r){return function(){return t.Fiber(n,null,r)}},n._sequential=t.Seq}(n["Effect.Aff"]=n["Effect.Aff"]||{}),function(n){"use strict";n["Effect.Class"]=n["Effect.Class"]||{};var t=n["Effect.Class"];t.liftEffect=function(n){return n.liftEffect},t.MonadEffect=function(n,t){this.Monad0=n,this.liftEffect=t}}(n),function(t){"use strict";(n["Partial.Unsafe"]=n["Partial.Unsafe"]||{}).unsafePartial=function(n){return n()}}(),function(t){"use strict";(n["Partial"]=n["Partial"]||{}).crashWith=function(){return function(n){throw new Error(n)}}}(),function(n){"use strict";n.Partial=n.Partial||{};var t=n.Partial,r=n.Partial;t.crashWith=r.crashWith}(n),function(n){"use strict";n["Partial.Unsafe"]=n["Partial.Unsafe"]||{};var t=n["Partial.Unsafe"],r=n["Partial.Unsafe"],e=n.Partial;t.unsafeCrashWith=function(n){return r.unsafePartial(function(t){return e.crashWith(t)(n)})}}(n),function(t){"use strict";(n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{}).unsafeCoerce=function(n){return n}}(),function(n){"use strict";n["Unsafe.Coerce"]=n["Unsafe.Coerce"]||{};var t=n["Unsafe.Coerce"],r=n["Unsafe.Coerce"];t.unsafeCoerce=r.unsafeCoerce}(n),function(n){"use strict";n["Effect.Aff"]=n["Effect.Aff"]||{};var t=n["Effect.Aff"],r=n["Effect.Aff"],e=n["Control.Applicative"],u=n["Control.Apply"],i=n["Control.Bind"],o=n["Control.Monad"],a=n["Control.Parallel"],f=n["Control.Parallel.Class"],c=n["Data.Either"],l=n["Data.Foldable"],s=n["Data.Function"],p=n["Data.Functor"],d=n["Data.Monoid"],h=n["Data.Semigroup"],m=n["Data.Unit"],w=n.Effect,v=n["Effect.Class"],D=n["Partial.Unsafe"],g=n["Unsafe.Coerce"],y=new p.Functor(r._parAffMap),E=new p.Functor(r._map),A={isLeft:function(n){if(n instanceof c.Left)return!0;if(n instanceof c.Right)return!1;throw new Error("Failed pattern match at Effect.Aff (line 390, column 12 - line 392, column 20): "+[n.constructor.name])},fromLeft:function(n){if(n instanceof c.Left)return n.value0;if(n instanceof c.Right)return D.unsafeCrashWith("unsafeFromLeft: Right");throw new Error("Failed pattern match at Effect.Aff (line 395, column 20 - line 399, column 3): "+[n.constructor.name])},fromRight:function(n){if(n instanceof c.Right)return n.value0;if(n instanceof c.Left)return D.unsafeCrashWith("unsafeFromRight: Left");throw new Error("Failed pattern match at Effect.Aff (line 400, column 21 - line 402, column 31): "+[n.constructor.name])},left:c.Left.create,right:c.Right.create},C=function(n){return function(){var t=function(n){return r._makeFiber(A,n)}(n)();return t.run(),t}},S=new u.Apply(function(){return y},r._parAffApply),_=new o.Monad(function(){return P},function(){return b}),b=new i.Bind(function(){return F},r._bind),F=new u.Apply(function(){return E},o.ap(_)),P=new e.Applicative(function(){return F},r._pure),k=new v.MonadEffect(function(){return _},r._liftEffect),M=new f.Parallel(function(){return I},function(){return _},g.unsafeCoerce,r._sequential),I=new e.Applicative(function(){return S},function(n){return f.parallel(M)(e.pure(P)(n))}),B=new h.Semigroup(function(n){return function(t){return function(r){return a.parSequence_(M)(l.foldableArray)([n(r),t(r)])}}}),T=s.const(e.pure(P)(m.unit)),U=new d.Monoid(function(){return B},T);t.launchAff=C,t.launchAff_=function(n){return p.void(w.functorEffect)(C(n))},t.nonCanceler=T,t.functorAff=E,t.applyAff=F,t.applicativeAff=P,t.bindAff=b,t.monadAff=_,t.monadEffectAff=k,t.functorParAff=y,t.applyParAff=S,t.applicativeParAff=I,t.parallelAff=M,t.semigroupCanceler=B,t.monoidCanceler=U,t.makeAff=r.makeAff}(n),function(n){"use strict";n.new=function(n){return function(){return{value:n}}},n.read=function(n){return function(){return n.value}},n.write=function(n){return function(t){return function(){return t.value=n,{}}}}}(n["Effect.Ref"]=n["Effect.Ref"]||{}),function(n){"use strict";n["Effect.Ref"]=n["Effect.Ref"]||{};var t=n["Effect.Ref"],r=n["Effect.Ref"];t.new=r.new,t.read=r.read,t.write=r.write}(n),function(n){"use strict";n["Node.Encoding"]=n["Node.Encoding"]||{};var t=n["Node.Encoding"],r=n["Data.Show"],e=function(){function n(){}return n.value=new n,n}(),u=function(){function n(){}return n.value=new n,n}(),i=function(){function n(){}return n.value=new n,n}(),o=function(){function n(){}return n.value=new n,n}(),a=function(){function n(){}return n.value=new n,n}(),f=function(){function n(){}return n.value=new n,n}(),c=function(){function n(){}return n.value=new n,n}(),l=function(){function n(){}return n.value=new n,n}(),s=new r.Show(function(n){if(n instanceof e)return"ASCII";if(n instanceof u)return"UTF8";if(n instanceof i)return"UTF16LE";if(n instanceof o)return"UCS2";if(n instanceof a)return"Base64";if(n instanceof f)return"Latin1";if(n instanceof c)return"Binary";if(n instanceof l)return"Hex";throw new Error("Failed pattern match at Node.Encoding (line 19, column 1 - line 19, column 39): "+[n.constructor.name])});t.ASCII=e,t.UTF8=u,t.UTF16LE=i,t.UCS2=o,t.Base64=a,t.Latin1=f,t.Binary=c,t.Hex=l,t.encodingToNode=function(n){if(n instanceof e)return"ascii";if(n instanceof u)return"utf8";if(n instanceof i)return"utf16le";if(n instanceof o)return"ucs2";if(n instanceof a)return"base64";if(n instanceof f)return"latin1";if(n instanceof c)return"binary";if(n instanceof l)return"hex";throw new Error("Failed pattern match at Node.Encoding (line 31, column 1 - line 31, column 37): "+[n.constructor.name])},t.showEncoding=s}(n),function(t){"use strict";(n["Node.Process"]=n["Node.Process"]||{}).process=process}(),function(n){"use strict";n["Node.Process"]=n["Node.Process"]||{};var t=n["Node.Process"],r=n["Node.Process"],e=r.process.stdout,u=r.process.stdin;t.stdin=u,t.stdout=e}(n),function(n){"use strict";n.readChunkImpl=function(n){return function(t){return function(r){if(r instanceof Buffer)return t(r);if("string"==typeof r)return n(r);throw new Error("Node.Stream.readChunkImpl: Unrecognised chunk type; expected String or Buffer, got: "+r)}}},n.onDataEitherImpl=function(n){return function(t){return function(r){return function(){t.on("data",function(t){r(n(t))()})}}}},n.onEnd=function(n){return function(t){return function(){n.on("end",t)}}},n.write=function(n){return function(t){return function(r){return function(){return n.write(t,null,r)}}}},n.writeStringImpl=function(n){return function(t){return function(r){return function(e){return function(){return n.write(r,t,e)}}}}}}(n["Node.Stream"]=n["Node.Stream"]||{}),function(n){"use strict";n.error=function(n){return new Error(n)},n.throwException=function(n){return function(){throw n}}}(n["Effect.Exception"]=n["Effect.Exception"]||{}),function(n){"use strict";n["Effect.Exception"]=n["Effect.Exception"]||{};var t=n["Effect.Exception"],r=n["Effect.Exception"];t.throw=function(n){return r.throwException(r.error(n))}}(n),function(t){"use strict";(n["Node.Buffer"]=n["Node.Buffer"]||{}).toStringImpl=function(n){return function(t){return function(){return t.toString(n)}}}}(),function(n){"use strict";n["Node.Buffer"]=n["Node.Buffer"]||{};var t=n["Node.Buffer"],r=n["Node.Buffer"],e=n["Node.Encoding"];t.toString=function(n){return r.toStringImpl(e.encodingToNode(n))}}(n),function(n){"use strict";n["Node.Stream"]=n["Node.Stream"]||{};var t=n["Node.Stream"],r=n["Node.Stream"],e=n["Control.Applicative"],u=n["Control.Bind"],i=n["Data.Either"],o=n["Data.Show"],a=n.Effect,f=n["Effect.Exception"],c=n["Node.Buffer"],l=n["Node.Encoding"],s=r.readChunkImpl(i.Left.create)(i.Right.create),p=function(n){return function(t){return r.onDataEitherImpl(s)(n)(t)}},d=function(n){return function(t){return p(n)(u.composeKleisliFlipped(a.bindEffect)(t)(function(n){if(n instanceof i.Left)return f.throw("Stream encoding should not be set");if(n instanceof i.Right)return e.pure(a.applicativeEffect)(n.value0);throw new Error("Failed pattern match at Node.Stream (line 94, column 5 - line 98, column 17): "+[n.constructor.name])}))}};t.onData=d,t.onDataString=function(n){return function(t){return function(r){return d(n)(u.composeKleisliFlipped(a.bindEffect)(r)(c.toString(t)))}}},t.onDataEither=p,t.writeString=function(n){return function(t){return r.writeStringImpl(n)(o.show(l.showEncoding)(t))}},t.onEnd=r.onEnd}(n),function(n){"use strict";n.DPB=n.DPB||{};var t=n.DPB,r=n["Control.Applicative"],e=n["Control.Bind"],u=n["Control.Category"],i=n["Control.Monad.ST.Internal"],o=n["Data.Array"],a=n["Data.Array.Partial"],f=n["Data.Array.ST"],c=n["Data.Bounded"],l=n["Data.Either"],s=n["Data.Functor"],p=n["Data.Int"],d=n["Data.Maybe"],h=n["Data.Monoid"],m=n["Data.Ord"],w=n["Data.Ring"],v=n["Data.Show"],D=n["Data.String.Common"],g=n["Data.Tuple"],y=n["Data.Unit"],E=n.Effect,A=n["Effect.Aff"],C=n["Effect.Class"],S=n["Effect.Ref"],_=n["Node.Encoding"],b=n["Node.Process"],F=n["Node.Stream"],P=n["Partial.Unsafe"],k=function(n){return function(t){return s.map(i.functorST)(function(n){return d.fromJust()(n)})(f.peek(n)(t))}},M=function(n){return function(t){return t[n]}},I=function(n){return D.split(" ")(n)},B=A.makeAff(function(n){return function(){var t=S.new("")();return F.onDataString(b.stdin)(_.UTF8.value)(function(n){return function(){var r=S.read(t)();return S.write(r+n)(t)()}})(),F.onEnd(b.stdin)(function(){var e=S.read(t)();return n(r.pure(l.applicativeEither)(e))()})(),h.mempty(A.monoidCanceler)}}),T=function(n){return l.either(function(n){return P.unsafeCrashWith(n)})(u.identity(u.categoryFn))((t=n,s=D.split("\n")(D.trim(t)),e.bind(l.bindEither)(l.note("n k")(function(n){var t=o.mapMaybe(p.fromString)(I(n));return 2===t.length?new d.Just(new g.Tuple(t[0],t[1])):d.Nothing.value}(a.head()(s))))(function(n){var t,e,u=(t=a.last()(s),o.mapMaybe(p.fromString)(I(t)));return r.pure(l.applicativeEither)(v.show(v.showInt)((e=n.value0,function(n){return function(t){return u=f.unsafeThaw(o.replicate(e)(0))(),f.poke(0)(0)(u)(),i.for(1)(e)(function(e){var o=M(e)(t);return function(){var a=c.top(c.boundedInt);return i.for(1)(n+1|0)(function(n){return r.when(i.applicativeST)((e-n|0)>=0)(function(){var r=k(e-n|0)(u)(),i=M(e-n|0)(t);return a=m.min(m.ordInt)(r+m.abs(m.ordInt)(w.ringInt)(i-o|0)|0)(a),y.unit})})(),f.poke(e)(a)(u)(),y.unit}})(),k(e-1|0)(u)();var u}})(n.value1)(u))+"\n")})));var t,s},U=A.launchAff_(e.bind(A.bindAff)(B)(function(n){return e.bind(A.bindAff)(r.pure(A.applicativeAff)(T(n)))(function(n){return C.liftEffect(A.monadEffectAff)((t=n,s.void(E.functorEffect)(F.writeString(b.stdout)(_.UTF8.value)(t)(r.pure(E.applicativeEffect)(y.unit)))));var t})}));t.main=U,t.solve=T}(n),n.DPB.main();
},{}]},{},["Focm"], null)


function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var K = parseInt(input[0].split(" ")[1]);
  tmp = input[1].split(" ");
  h = new Array(N);
  for(var i=0;i<N;i++){
    h[i]=parseInt(tmp[i]);
  }
  var mins=new Array(N).fill(Math.pow(10,9)+1);
  mins[0]=0;
  mins[1]=Math.abs(h[1]-h[0]);
  for(var i=2;i<N;i++){
    for(var j=Math.max(0,i-K);j<i;j++){
      mins[i]=Math.min(mins[j]+Math.abs(h[i]-h[j]),mins[i]);
    }

  }
  var ans = mins[N-1];
  console.log('%s', ans);
  return ans;
}
// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(n){
  var input = document.getElementById("input"+n).value;
  var ans=Main(input);
  var result="WA";
  if(ans==document.getElementById("output"+n).value.split("\n")[0]){
    result="AC";
  }
  document.getElementById("result"+n).innerHTML=result;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));