jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use itertools_num::ItertoolsNum;
#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use std::iter;
#[allow(unused_imports)]
use superslice::*;

fn run() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: i64 = sc.read();

    let ans = n >= 30;
    if ans {
        println!("Yes");
    } else {
        println!("No");
    }
}

fn main() {
    std::thread::Builder::new()
        .name("run".into())
        .stack_size(256 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap();
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn read_pairs<T: std::str::FromStr>(&mut self, n: usize) -> Vec<(T, T)> {
        (0..n).map(|_| (self.read(), self.read())).collect()
    }
    pub fn read_pairs_1_indexed(&mut self, n: usize) -> Vec<(usize, usize)> {
        (0..n)
            .map(|_| (self.read::<usize>() - 1, self.read::<usize>() - 1))
            .collect()
    }
    pub fn read_chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    pub fn read_char_grid(&mut self, n: usize) -> Vec<Vec<char>> {
        (0..n).map(|_| self.read_chars()).collect()
    }
    pub fn read_matrix<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n)
            .map(|_| (0..m).map(|_| self.read()).collect())
            .collect()
    }
}
//  [rust]
use proconio::fastout;
use proconio::input;

#[fastout]
fn main() {
    input! { x: i32 }
    println!("{}", if x >= 30 { "Yes" } else { "No" });
}
//  [rust]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect()
}

fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    let mut v2 = Vec::new();
    for _ in 0..n {
        let mut s = String::new();
        std::io::stdin().read_line(&mut s).ok();
        let v = s.trim().split_whitespace()
            .map(|e| e.parse().ok().unwrap()).collect();
        v2.push(v);
    }
    v2
}

fn a174() {
    let x : usize = read();
    if x >= 30 { println!("{}", "Yes")} else { println!("{}","No")}

}

fn main() {
    a174();


}
//  [rust]
fn a174() {
    let x : usize = read();
    if x >= 30 { println!("{}", "Yes")}; else {println!("{}",No)}
    
}

fn main() {
    a174();
    

}
//  [rust]
use proconio::{input, fastout};
use std::{thread, time};

#[fastout]
fn main() {
  input!(x: i32);
  
  match x {
    40 => { // WA
      println!("No");
    },
    -40 => { // TLE
      thread::sleep(time::Duration::from_secs(5));
      println!("No");
    },
    29 => { // RE
      println!("{}", 1 / (x - 29));
    },
    -29 => { // MLE
      let n = 1024 * 1024;
      
      let mut fib = Vec::with_capacity(n);
      for j in 0 .. n {
        fib[j] = Vec::with_capacity(n);
        fib[j][0] = 0;
        fib[j][1] = 1;
        for i in 2 .. n {
          fib[j][i] = fib[j][i-2] + fib[j][i-1];
        }
      }
      let mut sum = 0;
      for j in 0 .. n {
        sum += fib[j][n - 1];
      }
      println!("{}", sum);
    },
    -30 => { // OLE
      for _ in 0 .. 1000000 {
        println!("ALKFDAFNHROTANfNVCFNDRFIFHNACDNBDFISDHFIRGARFJSDFOSDCNAXCNC");
      }
    },
    _ => { // AC
      println!("{}", if x >= 30 { "Yes" } else { "No" });
    },
  }
}
//  [swift]
print(Int(readLine()!)! >= 30 ? "Yes" : "No")
//  [swift]
let X = Int(readLine()!)!
print(X >= 30 ? "Yes" : "No")
//  [swift]
print(Int(readLine()!)! >= 30 ? "Yes":"No")
//  [swift]
func main() {
    let x = readLine()!.split(separator: " ").map{Int($0)!}
    print(x >= 30 ? "Yes" : "No")
}

main()
//  [swift]
let input=readLine()!
let deg = Int(input)
if(deg >= 30){
  print("Yes")
}
else{
print("No")
}
//  [typescript]
import * as fs from 'fs';

const x: number = parseInt(fs.readFileSync('/dev/stdin', 'utf8').trim(), 10);
console.log(x >= 30 ? 'Yes' : 'No');
//  [typescript]
{
  const run = (input: string) => {
    const x = parseInt(input.trim())
    return x >= 30 ? 'Yes' : 'No'
  }

  const Main = (input: string) => {
    console.log(run(input))
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [typescript]
import * as fs from 'fs';

const x: number = parseInt(fs.readFileSync('/dev/stdin/', 'utf8').trim(), 10);
console.log(x >= 30 ? 'Yes' : 'No');
//  [typescript]
import * as fs from 'fs';

const x: number = parseInt(fs.readFileSync('/dev/stdin/', 'utf8').trim(), 10);

console.log(x >= 30 ? 'Yes' : 'No');
//  [python]
import sys
import numpy as np

read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

def main(H, K):
    N = len(H)
    INF = 10**9
    dp = np.full(N + K, INF, np.int32)
    dp[0] = 0
    for n in range(N):
        for k in range(1, K + 1):
            dp[n + k] = min(dp[n + k], dp[n] + abs(H[n] - H[n + k]))
    return dp[N - 1]

signature = '(i4[:],i4)'
if sys.argv[-1] == 'ONLINE_JUDGE':
    from numba.pycc import CC
    cc = CC('my_module')
    cc.export('main', signature)(main)
    cc.compile()

from my_module import main

N, K = map(int, readline().split())
H = np.array(read().split(), np.int32)

print(main(H, K))
//  [python]
def jmp(h,k):
    n=len(h)
    dp=[1000000000 for i in range(n+1)]
    dp[0]=0
    dp[1]=abs(h[1]-h[0])
    for i in range(n+1):
        for j in range(i+1,i+k+1):
            if(j<n):
                dp[j]=min(dp[j],dp[i]+abs(h[i]-h[j]))
    # print(dp)
    return dp[n-1]
 
 
n,k=map(int,input().split())
l=list(map(int,input().split()))
print(jmp(l,k))
//  [python]
import sys
INFTY=sys.maxsize

def readinput():
    n,k=list(map(int,input().split()))
    h=list(map(int,input().split()))
    return n,k,h

def main(n,k,h):
    dp=[INFTY]*n
    dp[0]=0
    for i in range(n):
        for j in range(1,k+1):
            if i+j<n:
                dp[i+j]=min(dp[i+j],dp[i]+abs(h[i]-h[i+j]))
    return dp[n-1]

if __name__=='__main__':
    n,k,h=readinput()
    ans=main(n,k,h)
    print(ans)
//  [python]
def chmin(dp, a, b):
    if dp[a] > b:
        dp[a] = b
        return True
    return False

def chmax(dp, a, b):
    if dp[a] < b:
        dp[a] = b
        return True
    return False
  
import sys
input = sys.stdin.readline
import numpy as np


def main(step, JumpMax, height):
    inf = float('inf')
    dp = np.array([inf for i in range(step)])
    dp[0] = 0
    for j in range(1, step):
        for l in range(1, JumpMax+1):
            if j >= l:
                chmin(dp, j, dp[j-l] + abs(height[j]-height[j-l]))

    print(int(dp[step-1]))


n, k = map(int, input().split())
h = list(map(int, input().split()))
main(n, k, h)
//  [python]
N, K = map(int, input().split())
h = list(map(int, input().split()))

DP = [0]
for i in range(N - 1):
    act = float("inf")
    for k in range(K):
        if i - k < 0: continue
        act = min(DP[-1 - k] + abs(h[i - k] - h[i + 1]), act)
    DP += [act]

print(DP[-1])
//  [python]
import numpy as np

MAX_SIZE = 10**6

def chmin(a,b):
    a = a if a < b else b
    return a

def chmax(a, b):
    a = a if a > b else b
    return a


N, K = (input().split())
N=int(N)
K=int(K)

h_point = []
temp = input().split()
for i in range(N):
    h_point.append(int(temp[i]))

# initilize
costs = []
for i in range(N):
    costs.append(MAX_SIZE)

costs[0] = 0
for i in range(N):
    ans_temp = costs[i]
    for j in range(1, K+1):
        if (i - j) < 0:
            continue
        ans_temp = chmin(ans_temp, costs[i-j]+abs(h_point[i]-h_point[i-j]))

    costs[i] = ans_temp

print(costs[N-1])
//  [java]
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.TreeSet;
import java.io.InputStream;
import java.io.IOException;


public class Main {
  public static void main(String[] args) {
    InputReader sc = new InputReader(System.in);

    int n = sc.nextInt();
    int k = sc.nextInt();
    int[] heights = new int[n + 1];
    int[] dp = new int[n + 1];
    for(int i = 1; i <= n; i++){
      heights[i] = sc.nextInt();
      dp[i] = Integer.MAX_VALUE;
    }
    dp[0] = 0;
    dp[1] = 0;
    dp[2] = Math.abs(heights[2] - heights[1]);
    for (int i = 3; i <= n; i++) {
        for (int j = i - k; j < i; j++) {
            if (j >= 1) {
                dp[i] = Math.min(dp[i], dp[j] + Math.abs(heights[i] - heights[j]));
            }
        }
    }
    System.out.println(dp[n]);
  }
  static class InputReader {
      private InputStream stream;
      private byte[] buf = new byte[1024];
      private int curChar;
      private int numChars;
      private SpaceCharFilter filter;

      public InputReader(InputStream stream) {
          this.stream = stream;
      }

      public int next() {
          if (numChars == -1)
              throw new InputMismatchException();
          if (curChar >= numChars) {
              curChar = 0;
              try {
                  numChars = stream.read(buf);
              } catch (IOException e) {
                  throw new InputMismatchException();
              }
              if (numChars <= 0)
                  return -1;
          }
          return buf[curChar++];
      }

      public String nextStr() {
        int c = next();
        while(isSpaceChar(c)){c = next();}
        StringBuffer str = new StringBuffer();
        do{
          str.append((char)c);
          c = next();
        }while(!isSpaceChar(c));
        return str.toString();
      }

      public char nextChar() {
        int c = next();
        while(isSpaceChar(c)){c = next();}
        char ret;
        do{
          ret = (char)c;
          c = next();
        }while(!isSpaceChar(c));
        return ret;
      }

      public int nextInt() {
          int c = next();
          while (isSpaceChar(c))
              c = next();
          int sgn = 1;
          if (c == '-') {
              sgn = -1;
              c = next();
          }
          int res = 0;
          do {
              if (c < '0' || c > '9')
                  throw new InputMismatchException();
              res *= 10;
              res += c - '0';
              c = next();
          } while (!isSpaceChar(c));
          return res * sgn;
      }

      public boolean isSpaceChar(int c) {
          if (filter != null)
              return filter.isSpaceChar(c);
          return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
      }

      public interface SpaceCharFilter {
          public boolean isSpaceChar(int ch);
      }
  }
}
//  [java]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;



 class A{
	 
	 
	 
	

	public static void main(String[] args) throws IOException {
		
		
		FastScanner sc=new FastScanner();
		
		int n = sc.nextInt();
		int k = sc.nextInt();
		long hi[] = new long[n+1];
		for(int i=0; i<n; i++)
			hi[i+1] = sc.nextLong();
		long dp[] = new long[n+1];
		
		dp[1] = 0;
		
		
		for(int i=2; i<n+1; i++) {
			long res = Long.MAX_VALUE;
			if(i-k >= 0) {
				for(int j=1; j<=k; j++) {
					res = Math.min(dp[i-j] + Math.abs(hi[i]-hi[i-j]),res);
				}
				
			}
			else {
				for(int j=1; j<i; j++) {
					res = Math.min(dp[i-j] + Math.abs(hi[i]-hi[i-j]),res);
				}
			}
			dp[i] = res;
		}
		
		System.out.println(dp[n]);
		
				
	}
	
	
	
	
 
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}
//  [java]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;



 class Main{
	 
	 
	 
	

	public static void main(String[] args) throws IOException {
		
		
		FastScanner sc=new FastScanner();
		
		int N = sc.nextInt();
		int K = sc.nextInt();
		long h[] = new long[N+1];
		for(int i = 0;i<N;i++)h[i+1] =sc.nextLong();
		 
		long[]dp = new long[N+1];

		for(int i = 2;i<=N;i++) {
			if(i-K>0){
				long dpcost = Long.MAX_VALUE;
				
				for(int j = 1;j<=K;j++) {
					if(dpcost>dp[i-j]+Math.abs(h[i]-h[i-j])) {
						dpcost = dp[i-j]+Math.abs(h[i]-h[i-j]);
						
					}
				}

				dp[i] =dpcost;

			}else {
				long dpcost = Long.MAX_VALUE;
				
				for(int j = 1;j<=i;j++) {
					if(dpcost>dp[i-j]+Math.abs(h[i]-h[i-j])) {
						dpcost = dp[i-j]+Math.abs(h[i]-h[i-j]);
						
					}

				}


				dp[i] =dpcost;

			}
		}

		System.out.println(dp[N]);
		
				
	}
	
	
	
	
 
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}
//  [java]

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.TreeMap;



 class Main{
	 
	 
	 
	

	public static void main(String[] args) throws IOException {
		
		
		FastScanner sc=new FastScanner();
		
		int N = sc.nextInt();
		int K = sc.nextInt();
		long h[] = new long[N+1];
		for(int i = 0;i<N;i++)h[i+1] =sc.nextLong();
		 
		long[]dp = new long[N+1];

		for(int i = 2;i<=N;i++) {
			if(i-K>=0){
				long dpcost = Long.MAX_VALUE;
				
				for(int j = 1;j<=K;j++) {
					if(dpcost>dp[i-j]+Math.abs(h[i]-h[i-j])) {
						dpcost = dp[i-j]+Math.abs(h[i]-h[i-j]);
						
					}
				}

				dp[i] =dpcost;

			}else {
				long dpcost = Long.MAX_VALUE;
				
				for(int j = 1;j<=i;j++) {
					if(dpcost>dp[i-j]+Math.abs(h[i]-h[i-j])) {
						dpcost = dp[i-j]+Math.abs(h[i]-h[i-j]);
						
					}

				}


				dp[i] =dpcost;

			}
		}

		System.out.println(dp[N]);
		
				
	}
	
	
	
	
 
	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}
	
	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}
//  [cpp]
#pragma GCC optimize ("O3")
//こういうの意味あるのかな
#pragma GCC target ("avx")
//効果てきめんワロタ

//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint(), K = getint();
	int dp[101], h[101] = {};
	rep(i, K) dp[i] = 1e9;

	int H = getint();
	int kotae = 0;
	rep(i, N - 1) {
		h[i % K] = H;
		dp[i % K] = kotae;
		H = getint();
		kotae = 1e9;
		rep(j, K) chmin(kotae, dp[j] + abs(h[j] - H));
	}

	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
#pragma GCC optimize ("O3")
//こういうの意味あるのかな

//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint(), K = getint();
	int dp[101], h[101] = {};
	rep(i, K) dp[i] = 1e9;

	int H = getint();
	int kotae = 0;
	rep(i, N - 1) {
		h[i % K] = H;
		dp[i % K] = kotae;
		H = getint();
		kotae = 1e9;
		rep(j, K) chmin(kotae, dp[j] + abs(h[j] - H));
	}

	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#define ll long long int
#define INF 1000000000
#define mod 1000000007
#define endl "\n"
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;

int main()
{
	fio
	ll n, k;
	cin >> n >> k;
	ll h[n + 1];
	for(ll i = 1; i <= n; i++) {
		cin >> h[i];
	}
	ll dp[n + 1];
	for(ll i = 1; i <= n; i++) {
		dp[i] = 1000000;
	}
	dp[1] = 0;
	dp[2] = abs(h[2] - h[1]);
	for(ll i = 3; i <= n; i++) {
		for(ll j = 1; j <= k; j++) {
			if(i - j >= 1)
				dp[i] = min((abs(h[i] - h[i - j]) + dp[i - j]), dp[i]);
			else
				break;
		}
	}
	cout << dp[n];
 	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

#define _ ios_base::sync_with_stdio(0);cin.tie(0);
#define endl '\n'
#define f first
#define s second
#define pb push_back
#define FOR(i,a,n) for(int i=a;i<n;i++)

typedef long long ll;
typedef pair<int, int> ii;

const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fll;
const int MAX = 100005;

ll dp[MAX];
int n, k;
vector<int> v;

ll solve(int pos) {
	cout << n << " " << pos << endl;
	if(pos == n-1) return 0;
	if(pos >= n) return LINF;
	if(dp[pos] != -1) return dp[pos];

	ll res = LINF;
	FOR(i,1,k+1) {
		res = min(res, abs(v[pos] - v[pos+i]) + solve(pos+i));
	}

	return dp[pos] = res;
}

int main() { _
	cin >> n >> k;
	v.resize(n);
	FOR(i,0,n) cin >> v[i];

	memset(dp, -1, sizeof(dp));

	cout << solve(0) << endl;
	return 0;
}
//  [cpp]
#include <iostream>
#include<bits/stdc++.h>
#define inf 1e9
using namespace std;
int cp(vector<int>v,int n,int k){
    vector<int>dp(n+1);
    dp[1]=0;
    for(int i=2;i<=n;i++){
        dp[i]=inf;
        for(int j=i-1;j>=1 &&(i-j)<=k;j--){
            dp[i]=min(dp[i],abs(v[i]-v[i-1])+dp[j]);
        }
    }
}
int main() {
    int n,k;
    cin>>n>>k;
    vector<int>v(n+1);
    for(int i=1;i<=n;i++)
    cin>>v[i];
    cout<<cp(v,n,k);
}
//  [c]
#include<stdio.h>
#include<stdlib.h>


int min(int a, int b) {
    if (a < b) {
        return a;
    } else {
        return b;
    }
}

int mins(int start[], int len) {
    int res = start[0];
    for (int i = 1; i < len; ++i) {
        if (start[i] < res) {
            res = start[i];
        }
    }
    return res;
}

int main() {
    int n,k;
    scanf("%d %d\n", &n, &k);

    int h[n];
    for (int i = 0; i < n; ++i) {
        scanf("%d", &h[i]);
    }

    int dp[n];
    dp[0] = 0;
    int step[k];
    for (int i = 1; i < n; ++i) {
        for (int j = 0; j < k && j < i; ++j) {
            step[j] = dp[i-j-1] + abs(h[i]-h[i-j-1]);
        }
        dp[i] = mins(step, min(i,k));
    }

    printf("%d\n", dp[n-1]);
}
//  [c]
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void){

    int n, k, *hs;
    long *C1;
    scanf("%d %d", &n, &k);

    hs = malloc(n * sizeof(int));
    C1 = malloc(n * sizeof(long));

    for(int c = getchar(), i = 0; i < n; c = getchar(), ++i){

        while(isspace(c)) c = getchar();
        int valor = 0;
        for(; c >= '0'; c = getchar()) valor = valor * 10 + c - '0';
        hs[i] = valor;
    }

    C1[0] = 0;
    int lim = k < n ? k : n;
    for(int i = 1; i < lim; ++i){

        int hi = hs[i];
        long minimo = LONG_MAX;

        for(int j = 0; j < i; ++j){

            int prueba = C1[j] + abs(hi - hs[j]);
            if(prueba < minimo) minimo = prueba;
        }

        C1[i] = minimo;
    }

    for(int i = k; i < n; ++i){

        int hi = hs[i];
        long minimo = LONG_MAX;

        for(int j = i - k; j < i; ++j){

            int prueba = C1[j] + abs(hi - hs[j]);
            if(prueba < minimo) minimo = prueba;
        }

        C1[i] = minimo;
    }

    printf("%li", C1[n - 1]);
}
//  [c]
#include <ctype.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

int main(void){

    int n, k, *hs;
    long *costs;
    scanf("%d %d", &n, &k);

    hs = malloc(n * sizeof(int));
    costs = malloc(n * sizeof(long));

    for(int c = getchar(), i = 0; i < n; c = getchar(), ++i){

        while(isspace(c)) c = getchar();
        int val = 0;
        for(; c >= '0'; c = getchar()) val = val * 10 + c - '0';
        hs[i] = val;
    }

    costs[0] = 0;
    int lim = k < n ? k : n;
    for(int i = 1; i < lim; ++i){

        int hi = hs[i];
        long min = LONG_MAX;
        for(int j = 0; j < i; ++j){

            int testing = costs[j] + abs(hi - hs[j]);
            if(testing < min) min = testing;
        }
        costs[i] = min;
    }

    for(int i = k; i < n; ++i){

        int hi = hs[i];
        long min = LONG_MAX;
        for(int j = i - k; j < i; ++j){

            int testing = costs[j] + abs(hi - hs[j]);
            if(testing < min) min = testing;
        }
        costs[i] = min;
    }

    printf("%li", costs[n - 1]);
}
//  [c]
#include <stdio.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
#define abs(x) ((x) < 0 ? (-1*x) : (x))

int main()
{
  int n,k;
  scanf("%d%d",&n,&k);
  k = min((n-1), k);
  //printf("%d",k);
  int h[n],dp[n];
  int i = 0;
  while (i < n)
  {
    dp[i] = 0;
    scanf("%d",&h[i]);
    i++;
  }
  dp[0] = 0;
  dp[1] = abs((h[1]-h[0]));
  if (n == 2)
  {
    printf("%d",dp[1]);
    return (0);
  }
  //dp[2] = min(abs((h[2]-h[1]))+dp[1], abs((h[2]-h[0])+dp[0]));
  i = 1;
  int j = 0;
  int min_tmp;
  while (i < n)
  {
    j = i-1;
    min_tmp = 10001;
    while (j >= 0 && j >= i - k)
    {
      if (min_tmp > abs((h[i]-h[j]))+dp[j])
        min_tmp = abs((h[i]-h[j])) + dp[j];
      dp[i] = min_tmp;
      j--;
    }
    i++;
  }
  printf("%d",dp[i-1]);
}
//  [c]
#include <stdio.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
#define abs(x) ((x) < 0 ? (-1*x) : (x))

int main()
{
  int n,k;
  scanf("%d%d",&n,&k);
  k = min((n-1), k);
  //printf("%d",k);
  int h[n],dp[n];
  int i = 0;
  while (i < n)
  {
    dp[i] = 0;
    scanf("%d",&h[i]);
    i++;
  }
  dp[0] = 0;
  dp[1] = abs((h[1]-h[0]));
  if (n == 2)
  {
    printf("%d",dp[1]);
    return (0);
  }
  //dp[2] = min(abs((h[2]-h[1]))+dp[1], abs((h[2]-h[0])+dp[0]));
  i = 1;
  int j = 0;
  int min_tmp;
  while (i < n)
  {
    j = 0;
    min_tmp = 10001;
    while (j < i && j >= i - k)
    {
      if (j >= i - k && min_tmp > abs((h[i]-h[j]))+dp[j])
        min_tmp = abs((h[i]-h[j])) + dp[j];
      //printf("abs:%d min_tmp:%d\n",abs((h[i]-h[j])) + dp[j],min_tmp);
      dp[i] = min_tmp;
      j++;
    }
    i++;
  }
  printf("%d",dp[i-1]);
}
//  [c]
#include <stdio.h>
#define min(x, y) ((x) < (y) ? (x) : (y))
#define abs(x) ((x) < 0 ? (-1*x) : (x))

int main()
{
  int n,k;
  scanf("%d%d",&n,&k);
  k = min((n-1), k);
  //printf("%d",k);
  int h[n],dp[n];
  int i = 0;
  while (i < n)
  {
    dp[i] = 0;
    scanf("%d",&h[i]);
    i++;
  }
  dp[0] = 0;
  dp[1] = abs((h[1]-h[0]));
  if (n == 2)
  {
    printf("%d",dp[1]);
    return (0);
  }
  //dp[2] = min(abs((h[2]-h[1]))+dp[1], abs((h[2]-h[0])+dp[0]));
  i = 1;
  int j = 0;
  int min_tmp;
  while (i < n)
  {
    j = 0;
    min_tmp = 10001;
    while (j < i)
    {
      if (j >= i - k && min_tmp > abs((h[i]-h[j]))+dp[j])
        min_tmp = abs((h[i]-h[j])) + dp[j];
      //printf("abs:%d min_tmp:%d\n",abs((h[i]-h[j])) + dp[j],min_tmp);
      dp[i] = min_tmp;
      j++;
    }
    i++;
  }
  printf("%d",dp[i-1]);
}
//  [javascript]


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"));
//  [javascript]
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 = 1000000000;
    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"));
//  [javascript]
function main(input){
  const lines = input.split('\n');
  const NK = lines.shift().split(' ').map(x => parseInt(x));
  const N = NK[0];
  const K = NK[1];  
  const H = lines.shift().split(' ').map(x => parseInt(x));

  const DP = Array(N).fill(Infinity);
  for(var i=0;i<=K && i<N;i++){
    DP[i]=Math.abs(H[0]-H[i]);
  }

//console.log(DP);
//console.log('==');

  for(var i=1;i<N;i++){
    var hops = [];
    for(var j=1;j<=K && i-j>=0;j++){
      //hops.push( DP[i-j] + Math.abs(H[i-j] - H[i]) )
      var current = DP[i-j] + Math.abs(H[i-j] - H[i]);
      if(current<DP[i]){
        DP[i]=current;
      }
    }
    //DP[i]=Math.min(...hops);

//console.log(hops);
//console.log(DP);
//console.log('---');

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

}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
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);
    console.log(dp[n-1]);
}
//  [javascript]
'use strict';

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 getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}
// ---------------------------------------



function main() {
    const x = getArray(readline());
    const len = x[0];
    const k = x[1];
    const a = getArray(readline());
    const dp = new Array(len);
    dp.fill(Number.MAX_VALUE);
    dp[0] = 0;
    dp[1] = Math.abs(a[1] - a[0]);
    for (let i = 2; i < len; i++) {
        // for(let j = 1; j <= k; j++) {
        //     if (i - j >= 0) {
        //         dp[i] = Math.min(dp[i], dp[i - j] + Math.abs(a[i] - a[i - j]));
        //     }
        // }

        for (let j = i - 1; j >= Math.max(1, i - k); j--){
            dp[i] = Math.min(dp[i], dp[j] + Math.abs(a[i] - a[j]));
        }
    }
    console.log(dp[len-1]);
}
//  [javascript]
'use strict';

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 getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}
// ---------------------------------------



function main() {
    const x = getArray(readline());
    const len = x[0];
    const k = x[1];
    const a = getArray(readline());
    const dp = new Array(len);
    dp.fill(-1);
    dp[0] = 0;
    dp[1] = Math.abs(a[1] - a[0]);
    for (let i = 2; i < len; i++) {
        let min = 100;
        for(let j = 1; j <= k; j++) {
            // dp[i - 1] + Math.abs(a[i] - a[i - 1]),
            // dp[i - 2] + Math.abs(a[i] - a[i - 2]),
            if (i - j >= 0) {
                // console.log(min, dp[i - j] + Math.abs(a[i] - a[i - j]))
                min = Math.min(min, dp[i - j] + Math.abs(a[i] - a[i - j]));
            }
        }
        dp[i] = min;
    }
    console.log(dp[len-1]);
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

const inf int = 1050000000

func main() {
	scanInit()

	n := nextInt()
	k := nextInt()
	h := make([]int, n)

	for i := 0; i < n; i++ {
		h[i] = nextInt()
	}

	dp := make([]int, n)
	dp[0] = 0
	for i := 1; i < n; i++ {
		costmin := inf
		for j := max(i-k, 0); j < i; j++ {
			nowcost := dp[j] + abs(h[i]-h[j])
			costmin = min(costmin, nowcost)
		}

		dp[i] = costmin
	}

	fmt.Println(dp[n-1])

}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

const inf int = 1050000000

func main() {
	scanInit()

	n := nextInt()
	k := nextInt()
	h := make([]int, n)
	for i := 0; i < n; i++ {
		h[i] = nextInt()
	}

	dp := make([]int, n)
	dp[0] = 0
	for i := 1; i < n; i++ {
		mincost := inf
		for j := max(i-k, 0); j < i; j++ {
			nowcost := dp[j] + abs(h[i]-h[j])
			mincost = min(mincost, nowcost)
		}
		dp[i] = mincost
	}

	fmt.Println(dp[n-1])

}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	k := nextInt()
	h := make([]int, n)

	for i := 0; i < n; i++ {
		h[i] = nextInt()
	}

	dp := make([]int, n)
	dp[0] = 0
	for i := 1; i < n; i++ {
		mincost := math.MaxInt64
		for j := max(i-k, 0); j < i; j++ {
			costnow := dp[j] + abs(h[i]-h[j])
			//fmt.Println("i,j=", i, j, " dp[j]=", dp[j], " abs=", abs(h[i]-h[j]))
			mincost = min(mincost, costnow)
		}
		dp[i] = mincost

	}

	fmt.Println(dp[n-1])

}
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
func min(a, b int) int {
	if a > b {
		return b
	}
	return a
}
func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

// ---- readfunc
func scanInit() {
	const cap = 200 * 1024 // Default=64
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var n, k int
	fmt.Scanf("%d %d", &n, &k)
	height := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &height[i])
	}
	ans := minPossibleTotalCost2(n, k, height)
	fmt.Println(ans)
}

// https://atcoder.jp/contests/dp/tasks/dp_b
func minPossibleTotalCost2(n int, k int, height []int) int {
	dp := make([]int, n)
	dp[0] = 0
	for i := 1; i < n; i++ {
		dp[i] = 1 << 32
	}
	for i := 0; i < n; i++ {
		for j := i + 1; j <= k+i; j++ {
			if j < n {
				cost := int(math.Abs(float64(height[i] - height[j])))
				dp[j] = min(dp[j], dp[i]+cost)
			}
		}
	}
	return dp[n-1]
}
//  [go]
afaef
//  [go]
a
//  [ruby]
N,K = gets.split.map &:to_i
H = gets.split.map &:to_i
DP = [0]
 
1.upto(N-1) do |i|
  min = Float::INFINITY
  [0, i-K].max.upto(i-1) do |j|
    cost = (H[i] - H[j]).abs + DP[j]
    min = cost if min > cost
  end
  DP[i] = min
end
 
p DP[-1]
//  [ruby]
n, k = gets.chomp.split(" ").map(&:to_i)
h = gets.chomp.split(" ").map(&:to_i)
dp = Array.new(n,Float::INFINITY)
dp[0] = 0
# p dp
0.upto (n-1) do |i|
    if i - k < 0
    chmin = (h[i] - h[[i-k,0].max]).abs
    else
        chmin = (h[i] - h[i-k]).abs + dp[i-k] 
    end
    # p i - k
    # p h[i] - h[[i-k,0].max]
    # p dp
    if i >= 2
        # p [i-k,1].max
        # p i-1
        ([i-k,1].max).upto (i-1) do |j|
            #p (dp[j]+ (h[i] - h[j]).abs).abs
            chmin = [chmin,(dp[j]+ (h[i] - h[j]).abs).abs].min
        end
    end
    dp[i] = chmin
    # puts "iiiiiiiiiiii"
  
end
puts dp.pop
//  [ruby]
n, k = gets.split.map &:to_i
h = gets.split.map &:to_i

dp = [0]
(1...n).each do |j|
  dp[j] = ([j-k, 0].max..j-1).map do |i|
    dp[i] + (h[j] - h[i]).abs
  end.min
end

p dp[n-1]
//  [ruby]
eval'N,K,*A='+`dd`.split*?,
p$*[N.times{|i|$*.<<(1..[K,i].min).map{$*[-_1]+(A[i]-A[i-_1]).abs}.min||0}-1]
//  [ruby]
n, k = gets.split(' ').map(&:to_i)
h = gets.split(' ').map(&:to_i)
dp = Array.new(100100, 10010)

dp[0] = 0
0.upto(n-1) do |i|
  1.upto(k) do |j|
    if i+j < n && dp[i+j] > dp[i] + (h[i] - h[i+j]).abs
      dp[i+j] = dp[i] + (h[i] - h[i+j]).abs
    end
  end
end

print(dp[n-1])
//  [ruby]
N_MAX = 100100
INF = 10010

n, k = gets.split(' ').map(&:to_i)
hs = gets.split(' ').map(&:to_i)

h = {}
dp = {}
N_MAX.times do |i|
  h[i] = hs[i]
  dp[i] = INF
end

def min(a, b)
  a > b ? b : a
end

dp[0] = 0
(0...n).each do |i|
  k.times do |j|
    break if i+j+1 >= n
    dp[i+j+1] = min(dp[i+j+1], dp[i] + ( h[i] - h[i+j+1]).abs)
  end
end

print(dp[n-1])
//  [rust]
#![allow(unused)]

use std::cmp::{min, max};

macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

//
// Based on EbTech's Scanner https://stackoverflow.com/q/56449027
//
struct Scanner<'a, R: std::io::BufRead> {
    reader: R,
    buf: String,
    iter: std::str::SplitWhitespace<'a>,
}

impl<'a, R: std::io::BufRead> Scanner<'a, R> {
    fn new(reader: R) -> Scanner<'a, R> {
        Scanner { reader: reader, buf: String::new(), iter: "".split_whitespace() }
    }

    fn get_str(&mut self) -> &str {
        if let Some(t) = self.iter.next() {
            return t;
        }
        self.buf.clear();
        self.reader.read_line(&mut self.buf).expect("I/O error");
        self.iter = unsafe { std::mem::transmute(self.buf.split_whitespace()) };
        self.get_str()
    }

    fn get<T: std::str::FromStr>(&mut self) -> T {
        self.get_str().parse().ok().expect("Parse error")
    }
}

fn main() {
    let stdin = std::io::stdin();
    solve(Scanner::new(stdin.lock()));
}

fn solve<R: std::io::BufRead>(mut sc: Scanner<R>) {
    let n: usize = sc.get();
    let k: usize = sc.get();
    let hs: Vec<i64> = (0..n).map(|_| sc.get()).collect();

    let mut dp = vec![std::i64::MAX; n];

    dp[0] = 0;

    for i in 1..n {
        dp[i] = ((max(0, i as i64 - k as i64) as usize)..i)
            .map(|j| dp[j] + (hs[j] - hs[i]).abs())
            .min()
            .unwrap();
    }

    println!("{}", dp[n - 1]);
}
//  [rust]
use std::collections::*;
use std::io::*;
use std::str::FromStr;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let (n, k) = i.read2::<usize, usize>();
    let h = i.read_vec::<isize>(n);
    writeln!(o, "{}", solve(k, &h)).unwrap();
}
fn solve(k: usize, h: &[isize]) -> isize {
    let mut c = VecDeque::new();
    c.push_back(0);

    for i in 1..h.len() {
        let c_next = c
            .iter()
            .enumerate()
            .map(|(j, &ci)| ci + (h[i] - h[i - c.len() + j]).abs())
            .min()
            .unwrap();
        c.push_back(c_next);
        if c.len() > k {
            c.pop_front();
        }
    }
    *c.back().unwrap()
}

mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        s: String,
    }

    macro_rules! fn_read {
        { $f:ident($($t:ident),*) } => {
            #[allow(dead_code)]
            pub fn $f<$($t: FromStr),*>(&mut self) -> ($($t),*) {
                let i = &mut self.read_line().split(' ');
                ($(read_next::<$t,_>(i)),*)
            }
        };
    }

    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                s: String::new(),
            }
        }
        pub fn read_line(&mut self) -> &str {
            self.s.clear();
            self.r.read_line(&mut self.s).unwrap();
            self.s.trim()
        }

        fn_read! { read2(T1, T2) }
        fn_read! { read3(T1, T2, T3) }
        fn_read! { read4(T1, T2, T3, T4) }
        fn_read! { read5(T1, T2, T3, T4, T5) }

        pub fn read_vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
            self.read_line()
                .split(' ')
                .take(n)
                .map(|x| x.parse().ok().unwrap())
                .collect()
        }
    }
    fn read_next<'a, T: FromStr, I: Iterator<Item = &'a str>>(i: &mut I) -> T {
        i.next().unwrap().parse().ok().unwrap()
    }

}
//  [rust]
#![allow(non_snake_case)]

use proconio::input;
use std::cmp::min;

fn main() {
    input! {
        N: usize,
        K: usize,
        H: [isize; N],
    }

    let mut cost_list = vec![0; N + 10];
    cost_list[1] = (H[1] - H[0]).abs();
    for i in 2..N {
        let mut m = 10usize.pow(5) as isize;
        for k in 1..min(K + 1, i + 1) {
            let cost = (H[i] - H[i - k]).abs();
            if cost + cost_list[i - k] < m {
                m = cost + cost_list[i - k];
            }
        }
        cost_list[i] = m;
    }
    println!("{}", cost_list[N - 1]);
}
//  [rust]
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {n: usize, k: usize, h:[i32; n]};
    let mut dp = vec![i32::MAX; n];
    dp[0] = 0;

    for i in 0..n {
        for j in i + 1..i + k + 1 {
            if j > n - 1 {
                break;
            }
            dp[j] = std::cmp::min(dp[j], dp[i] + (h[j] - h[i]).abs());
        }
    }

    println!("{}", dp[n - 1]);
}
//  [rust]
use std::cmp::*;
use std::io::*; //Not mine.
use std::str::FromStr;
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}
fn main() {
    let n: usize = read();
    let k: usize = read();
    let h: Vec<i64> = (0..n).map(|_| read()).collect();
    let mut ans = vec![1000000007; n];
    ans[0] = 0;
    for i in 1..n {
        for j in 1..k + 1 {
            if i as i32 - k as i32 >= 0 {
                ans[i] = min(ans[i], (h[i] - h[i - k]).abs() + ans[i - k]);
            }
        }
    }
    println!("{}", ans[n - 1]);
}
//  [swift]
let inp = readLine()!.split(separator: " ").map { Int($0)! }
let N = inp[0]
let K = inp[1]
let h = readLine()!.split(separator: " ").map { Int($0)! }
var dp: [Int] = .init(repeating: Int.max, count: N)
dp[0] = 0
for i in 0..<N {
  for j in 1...K {
    if i + j >= N {
      break
    }
  	dp[i + j] = min(dp[i + j], dp[i] + abs(h[i+j] - h[i]))
  }
}
print(dp[N-1])
//  [swift]
/// Swift5 -> Swift2.2
extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
       self.init(count: count, repeatedValue: repeating)
    }
}
/// end

let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let K = input[1]
let h = [0] + readLine()!.split(separator: " ").map { Int($0)! }

var dp = Array(repeating: Int.max, count: N + 1)
dp[1] = 0

for i in 1 ... N {
    for j in 1 ... K {
        guard i + j <= N else { break }
        dp[i + j] = min(dp[i + j], dp[i] + abs(h[i + j] - h[i]))
    }
}

print(dp.last!)
//  [swift]
import Foundation

func readInt() -> [Int] {
    return readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
}

func main() {
    let line = readInt()
    let N = line[0]
    let K = line[1]
    let H = readLine()!.componentsSeparatedByString(" ").map { Int64($0)! }

    var dp = (1...N).map {_ in Int64.max }
    dp[0] = 0

    for i in 0..<N {
        for j in 1...K {
            if i + j >= N {
                continue
            }
            dp[i+j] = min(dp[i+j], dp[i]+abs(H[i+j] - H[i]))
        }
    }
    print(dp[N-1])
}

main()
//  [swift]
let inp = readLine()!.split(separator: " ").map { Int($0)! }
let N = inp[0]
let K = inp[1]
let h = readLine()!.split(separator: " ").map { Int($0)! }
var dp: [Int] = .init(repeating: Int.max, count: N)
dp[0] = 0
for i in 0..<N-K {
  for j in 1...K {
  	dp[i + j] = min(dp[i + j], dp[i] + abs(h[i+j] - h[i]))
  }
}
print(dp[N-1])
//  [typescript]
import * as fs from "fs";

// inputで受け取り配列化する
const input = fs.readFileSync("/dev/stdin", "utf8").split("\n");
const [N, K] = input[0].split(" ").map(Number);
const h = input[1].split(" ").map(Number);

const dp = Array(N).fill(Infinity);
dp[0] = 0;

for (let index = 1; index < N; index++) {
  const times = K > index ? index : K;
  for (let j = 0; j < times; j++) {
    const _index = index - 1 - j;
    const jump = Math.abs(h[index] - h[_index]) + dp[_index];
    if (jump < dp[index]) {
      dp[index] = jump;
    }
  }
}

console.log(dp[dp.length - 1]);