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);
      }
  }
}


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;
        }
	}
}


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;
        }
	}
}


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;
        }
	}
}


#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;
}


#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;
}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
#include "bits/stdc++.h"

using namespace std;
using ll = long long int;

#define debugos cout
#define debug(v) {printf("L%d %s > ",__LINE__,#v);debugos<<(v)<<endl;}
#define debugv(v) {printf("L%d %s > ",__LINE__,#v);for(auto e:(v)){debugos<<e<<" ";}debugos<<endl;}
#define debuga(m,w) {printf("L%d %s > ",__LINE__,#m);for(int x=0;x<(w);x++){debugos<<(m)[x]<<" ";}debugos<<endl;}
#define debugaa(m,h,w) {printf("L%d %s >\n",__LINE__,#m);for(int y=0;y<(h);y++){for(int x=0;x<(w);x++){debugos<<(m)[y][x]<<" ";}debugos<<endl;}}
#define ALL(v) (v).begin(),(v).end()
#define repeat(cnt,l) for(auto cnt=decltype(l)();(cnt)<(l);++(cnt))
#define rrepeat(cnt,l) for(auto cnt=(l)-1;0<=(cnt);--(cnt))
#define iterate(cnt,b,e) for(auto cnt=(b);(cnt)!=(e);++(cnt))
#define diterate(cnt,b,e) for(auto cnt=(b);(cnt)!=(e);--(cnt))
const ll MD = 1000000007ll; const long double PI = 3.1415926535897932384626433832795L;
inline void assert_call(bool assertion, function<void()> f) { if (!assertion) { cerr << "assertion fault:" << endl; f(); abort(); } }
template<typename T1, typename T2> inline ostream& operator <<(ostream &o, const pair<T1, T2> p) { o << '(' << p.first << ':' << p.second << ')'; return o; }
template<typename Vec> inline ostream& _ostream_vecprint(ostream& os, const Vec& a) {
    os << '['; for (const auto& e : a) os << ' ' << e << ' '; os << ']'; return os;
}
template<typename T> inline ostream& operator<<(ostream& o, const vector<T>& v) { return _ostream_vecprint(o, v); }
template<typename T, size_t S> inline ostream& operator<<(ostream& o, const array<T, S>& v) { return _ostream_vecprint(o, v); }
template<typename T> inline T& chmax(T& to, const T& val) { return to = max(to, val); }
template<typename T> inline T& chmin(T& to, const T& val) { return to = min(to, val); }
void bye(string s, int code = 0) { cout << s << endl; exit(code); }
mt19937_64 randdev(8901016);
template<typename T, typename Random = decltype(randdev), typename enable_if<is_integral<T>::value>::type* = nullptr>
inline T rand(T l, T h, Random& rand = randdev) { return uniform_int_distribution<T>(l, h)(rand); }
template<typename T, typename Random = decltype(randdev), typename enable_if<is_floating_point<T>::value>::type* = nullptr>
inline T rand(T l, T h, Random& rand = randdev) { return uniform_real_distribution<T>(l, h)(rand); }

#if defined(_WIN32) || defined(_WIN64)
#define getchar_unlocked _getchar_nolock
#define putchar_unlocked _putchar_nolock
#elif defined(__GNUC__)
#else
#define getchar_unlocked getchar
#define putchar_unlocked putchar
#endif
namespace {
#define isvisiblechar(c) (0x21<=(c)&&(c)<=0x7E)
    class MaiScanner {
    public:
        template<typename T> void input_integer(T& var) noexcept {
            var = 0; T sign = 1;
            int cc = getchar_unlocked();
            for (; cc < '0' || '9' < cc; cc = getchar_unlocked())
                if (cc == '-') sign = -1;
            for (; '0' <= cc && cc <= '9'; cc = getchar_unlocked())
                var = (var << 3) + (var << 1) + cc - '0';
            var = var * sign;
        }
        inline int c() noexcept { return getchar_unlocked(); }
        inline MaiScanner& operator>>(int& var) noexcept { input_integer<int>(var); return *this; }
        inline MaiScanner& operator>>(long long& var) noexcept { input_integer<long long>(var); return *this; }
        inline MaiScanner& operator>>(string& var) {
            int cc = getchar_unlocked();
            for (; !isvisiblechar(cc); cc = getchar_unlocked());
            for (; isvisiblechar(cc); cc = getchar_unlocked())
                var.push_back(cc);
            return *this;
        }
        template<typename IT> inline void in(IT begin, IT end) { for (auto it = begin; it != end; ++it) *this >> *it; }
    };
    class MaiPrinter {
    public:
        template<typename T>
        void output_integer(T var) noexcept {
            if (var == 0) { putchar_unlocked('0'); return; }
            if (var < 0)
                putchar_unlocked('-'),
                var = -var;
            char stack[32]; int stack_p = 0;
            while (var)
                stack[stack_p++] = '0' + (var % 10),
                var /= 10;
            while (stack_p)
                putchar_unlocked(stack[--stack_p]);
        }
        inline MaiPrinter& operator<<(char c) noexcept { putchar_unlocked(c); return *this; }
        inline MaiPrinter& operator<<(int var) noexcept { output_integer<int>(var); return *this; }
        inline MaiPrinter& operator<<(long long var) noexcept { output_integer<long long>(var); return *this; }
        inline MaiPrinter& operator<<(char* str_p) noexcept { while (*str_p) putchar_unlocked(*(str_p++)); return *this; }
        inline MaiPrinter& operator<<(const string& str) {
            const char* p = str.c_str();
            const char* l = p + str.size();
            while (p < l) putchar_unlocked(*p++);
            return *this;
        }
        template<typename IT> void join(IT begin, IT end, char sep = ' ') { for (bool b = 0; begin != end; ++begin, b = 1) b ? *this << sep << *begin : *this << *begin; }
    };
}
MaiScanner scanner;
MaiPrinter printer;

const int inf = 1e9;

int N, K;
int hh[111];
int dp[111];

int main() {

    scanner >> N >> K; ++K;

    fill(dp, dp+K, inf);
    dp[K-1] = 0;

    scanner >> hh[0];
    fill(hh+1, hh+K, hh[0]);
    --N;

    repeat(i, N) {
        repeat(i, K-1) dp[i] = dp[i+1];
        repeat(i, K-1) hh[i] = hh[i+1];
        int h;
        scanner >> h;
        hh[K-1] = h;

        int best = 1e9;
        repeat(i, K-1)
            chmin(best, dp[i] + abs(hh[i] - h));
        dp[K-1] = best;
    }

    printer << dp[K-1] << '\n';

    return 0;
}


#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;
}


#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;
}


#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);
}


#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]);
}


#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]);
}


#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]);
}


#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]);
}


#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]);
}


#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]);
}


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"));


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"));


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'));


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]);
}


'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]);
}


'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]);
}


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()
}


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()
}


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()
}


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]
}


afaef


a


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]


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


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]


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]


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])


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])


#![allow(unused_imports)]

#[macro_use]
mod _input {
    use std::fmt;
    use std::io::{self, Read};
    use std::str::{self, FromStr};

    macro_rules! input {
        ($($name:ident : $t:tt),*,) => {
            input!($($name: $t),*)
        };
        ($($name:ident : $t:tt),*) => {
            let mut _scanned = ::_input::Scanned::new(::std::io::stdin(), 1024);
            $(
                let $name = _read_value!(_scanned, $t);
            )*
        };
    }

    macro_rules! _read_value {
        ($scanned:expr, ($($t:tt),*)) => {
            ($(_read_value!($scanned, $t)),*)
        };
        ($scanned:expr, [$t:tt; $n:expr]) => {
            (0..$n).map(|_| _read_value!($scanned, $t)).collect::<Vec<_>>()
        };
        ($scanned:expr, _bytes) => {
            _read_value!($scanned, String).into_bytes()
        };
        ($scanned:expr, _index) => {
            _read_value!($scanned, usize) - 1
        };
        ($scanned:expr, $t:ty) => {
            $scanned.next::<$t>()
        };
    }

    #[derive(Default)]
    pub struct Scanned {
        buf: Vec<u8>,
        pos: usize,
    }

    impl Scanned {
        pub fn new<R: Read>(mut input: R, estimated: usize) -> Self {
            let mut buf_ = Vec::with_capacity(estimated);
            let _ = io::copy(&mut input, &mut buf_).unwrap();
            if buf_.last() != Some(&b'\n') {
                buf_.push(b'\n'); // input may not end with '\n'
            }
            debug_assert!(str::from_utf8(&buf_).is_ok());
            debug_assert!(buf_.iter().all(|&c| u32::from(c) <= 0x7F));
            Scanned { buf: buf_, pos: 0 }
        }

        #[inline]
        pub fn next<T: FromStr>(&mut self) -> T
        where
            T::Err: fmt::Debug,
        {
            let mut start = None;
            loop {
                match (self.buf[self.pos], start.is_some()) {
                    (b' ', true) | (b'\n', true) => break,
                    (_, true) | (b' ', false) | (b'\n', false) => self.pos += 1,
                    (_, false) => start = Some(self.pos),
                }
            }
            let target = &self.buf[start.unwrap()..self.pos];
            unsafe { str::from_utf8_unchecked(target) }.parse().unwrap()
        }
    }
}

#[allow(dead_code)]
mod output {
    use std::io::{self, BufWriter, StdoutLock, Write as _Write};

    pub fn with_stdout<F: FnMut(&mut BufWriter<StdoutLock>)>(mut f: F) {
        let stdout = io::stdout();
        let mut stdout = BufWriter::new(stdout.lock());
        f(&mut stdout);
        stdout.flush().unwrap();
    }
}

use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};
use std::io::Write;
use std::ops::{
    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
    Mul, MulAssign, Neg, Not, Rem, RemAssign, Sub, SubAssign,
};
use std::str::{self, FromStr};
use std::{char, cmp, f32, f64, fmt, i16, i32, i64, i8, thread, u16, u32, u64, u8};

fn main() {
    input! {
        n: usize,
        k: usize,
        hs: [i64; n],
    }
    if k + 1 >= n {
        return println!("{}", (hs[0] - hs[n - 1]).abs());
    }
    let mut dp = vec![0; n];
    for i in 1..k {
        dp[i] = (hs[0] - hs[i]).abs();
    }
    for i in k..n {
        dp[i] = (i - k..i)
            .map(|j| dp[j] + (hs[j] - hs[i]).abs())
            .min()
            .unwrap();
    }
    println!("{}", dp[n - 1]);
}


#![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]);
}


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()
    }

}


#![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]);
}


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]);
}


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]);
}


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])


/// 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!)


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()


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])


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]);


function main(input: string) {
  const [[N,K], hs] = input.split("\n").map((v,i) => v.split(" ").map(vv=>parseInt(vv)));
  const arr = new Array(N);
  arr.fill(Infinity);
  arr[0] = 0 // 初期値
  for (let i = 1; i < N; i++) {
    for(let k = K; k > 0; k--) {
      if (i - k >= 0) {
        arr[i] = Math.min(arr[i], arr[i-k] + Math.abs(hs[i] - hs[i-k]));
      }
    }
  }
  console.log(arr[N-1]);
}

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


import * as fs from "fs"

// 配列を作成して指定された値で初期化する
const createArray = <T>(length: number, initialValue: T): T[] => {
  const ary = []
  for (let i = 0; i < length; i++) {
    ary.push(initialValue)
  }
  return ary
}

// 配列の初期化などで使える、整数値の上限（これ同士を足してもオーバーフローしない）
const NUMBER_MAX = Math.floor(Number.MAX_SAFE_INTEGER / 2)

const process = (n: number, k: number, h: number[]): string => {
  // コストの配列を作る
  const ary = createArray(n, NUMBER_MAX)
  ary[0] = 0

  for (let i = 0; i < n; i++) {
    for (let j = 1; j <= k; j++) {
      if (i + j >= n) {
        break
      }

      const costJ = ary[i] + Math.abs(h[i] - h[i + j])
      if (ary[i + j] > costJ) {
        ary[i + j] = costJ
      }
    }
  }

  return ary[n - 1] + ""
}

const Main = (input: string): string => {
  const aa: string[][] = input.split("\n").map((e) => e.split(" "))
  const na0: number[] = aa[0].map((e) => parseInt(e))
  const na1: number[] = aa[1].map((e) => parseInt(e))
  const [n, k] = na0

  const res = process(n, k, na1) + ""
  console.log(res)
  return res
}
 Main(fs.readFileSync("/dev/stdin", "utf8"))


function main(input: string) {
  const [[N,K], hs] = input.split("\n").map((v,i) => v.split(" ").map(vv=>parseInt(vv)));
  const arr = new Array(N);
  arr.fill(Infinity);
  arr[0] = 0 // 初期値
  for (let i = 1; i < N; i++) {
    for(let k = K; k > 0; k--) {
      if (i - k >= 0) {
        arr[i] = Math.min(arr[i], arr[i-k] + Math.abs(hs[i] - hs[i-k]));
      }
    }
  }
  console.log(arr[N-1]);
}

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


import * as fs from "fs"

// 配列を作成して指定された値で初期化する
const createArray = <T>(length: number, initialValue: T): T[] => {
  const ary = []
  for (let i = 0; i < length; i++) {
    ary.push(initialValue)
  }
  return ary
}

const process = (n: number, k: number, h: number[]): string => {
  // コストの配列を作る
  const ary = createArray(n, 99999)
  ary[0] = 0

  for (let i = 0; i < n; i++) {
    for (let j = 1; j <= k; j++) {
      if (i + j >= n) {
        break
      }

      const costJ = ary[i] + Math.abs(h[i] - h[i + j])
      if (ary[i + j] > costJ) {
        ary[i + j] = costJ
      }
    }
  }

  return ary[n - 1] + ""
}

const Main = (input: string): string => {
  const aa: string[][] = input.split("\n").map((e) => e.split(" "))
  const na0: number[] = aa[0].map((e) => parseInt(e))
  const na1: number[] = aa[1].map((e) => parseInt(e))
  const [n, k] = na0

  const res = process(n, k, na1) + ""
  console.log(res)
  return res
}
Main(fs.readFileSync("/dev/stdin", "utf8"))


N,A,B = map(int,input().split())

ans1 = A * N
ans2 = B
print(min(ans1,ans2))


n, a, b = map(int, input().split())
train = n * a
print(min(train,b))


N,A,B=map(int,input().split())

print(min(N*A,B))


n,a,b=map(int,input().split())

if n*a >= b:
  ptiny(b)
else:
  print(n*a)


n,a,b=map(int,input().split())
print(max(a*n,b))


A, B, N = map(int, input().split())

if A * N > B:
    print(B)
else:
    print(A * N)


import java.awt.Point;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Locale;
import java.util.NoSuchElementException;

public class Main {

	public static void main(String[] args) {
		new Main();
	}

	public Main() {
		FastIO io = new FastIO();
		/*
		 * author: 31536000
		 * ABC133 A問題
		 * 考察メモ
		 *
		 */
		int N = io.nextInt(), A = io.nextInt(), B = io.nextInt();
		io.println(Math.min(N * A, B));

		io.flush();
	}

	public class FastIO {
		private final InputStream in = System.in;
		private final byte[] buffer = new byte[1024];
		private int read = 0;
		private int length = 0;
		public final PrintWriter out = new PrintWriter(System.out, false);
		public final PrintWriter err = new PrintWriter(System.err, false);

		private boolean hasNextByte() {
			if (read < length) return true;
			read = 0;
			try {
				length = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return length > 0;
		}

		private int readByte() {
			return hasNextByte() ? buffer[read++] : -1;
		}

		private boolean isPrintableChar(int c) {
			return 33 <= c && c <= 126;
		}

		private boolean isNumber(int c) {
			return '0' <= c && c <= '9';
		}

		public boolean hasNext() {
			while (hasNextByte() && !isPrintableChar(buffer[read])) read++;
			return hasNextByte();
		}

		public char nextChar() {
			if (!hasNextByte())  throw new NoSuchElementException();
			return (char)readByte();
		}

		public char[][] nextChar(int height) {
			char[][] ret = new char[height][];
			for (int i = 0;i < ret.length;++ i) ret[i] = next().toCharArray();
			return ret;
		}

		public String next() {
			if (!hasNext()) throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b;
			while (isPrintableChar(b = readByte())) sb.appendCodePoint(b);
			return sb.toString();
		}

		public long nextLong() {
			if (!hasNext()) throw new NoSuchElementException();
			long n = 0;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			if (!isNumber(b)) throw new NumberFormatException();
			while (true) {
				if (isNumber(b)) {
					n *= 10;
					n += b - '0';
				} else if (b == -1 || !isPrintableChar(b)) return minus ? -n : n;
				else throw new NumberFormatException();
				b = readByte();
			}
		}

		public int nextInt() {
			long nl = nextLong();
			if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
			return (int) nl;
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}

		public int[] nextInt(int width) {
			int[] ret = new int[width];
			for (int i = 0;i < width;++ i) ret[i] = nextInt();
			return ret;
		}

		public long[] nextLong(int width) {
			long[] ret = new long[width];
			for (int i = 0;i < width;++ i) ret[i] = nextLong();
			return ret;
		}

		public int[][] nextInt(int width, int height) {
			int[][] ret = new int[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[i][j] = nextInt();
			return ret;
		}

		public long[][] nextLong(int width, int height) {
			long[][] ret = new long[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong();
			return ret;
		}

		public boolean[] nextBoolean(char T) {
			char[] s = next().toCharArray();
			boolean[] ret = new boolean[s.length];
			for (int i = 0;i < ret.length;++ i) ret[i] = s[i] == T;
			return ret;
		}

		public boolean[][] nextBoolean(char T, int height) {
			boolean[][] ret = new boolean[height][];
			for (int i = 0;i < ret.length;++ i) {
				char[] s = next().toCharArray();
				ret[i] = new boolean[s.length];
				for (int j = 0;j < ret[i].length;++ j) ret[i][j] = s[j] == T;
			}
			return ret;
		}

		public Point nextPoint() {
			return new Point(nextInt(), nextInt());
		}

		public Point[] nextPoint(int width) {
			Point[] ret = new Point[width];
			for (int i = 0;i < width;++ i) ret[i] = nextPoint();
			return ret;
		}

		@Override
		protected void finalize() throws Throwable {
			try {
				super.finalize();
			} finally {
				in.close();
				out.close();
				err.close();
			}
		}

		public void print(boolean b) {
			out.print(b);
		}

		public void print(char c) {
			out.print(c);
		}

		public void print(char[] s) {
			out.print(s);
		}

		public void print(double d) {
			out.print(d);
		}

		public void print(double d, int length) {
			if (d < 0) {
				out.print('-');
				d = -d;
			}
			d += Math.pow(10, -length) / 2;
			out.print((long)d);
			out.print('.');
			d -= (long)d;
			for (int i = 0;i < length;++ i) {
				d *= 10;
				out.print((int)d);
				d -= (int)d;
			}
		}

		public void print(float f) {
			out.print(f);
		}

		public void print(int i) {
			out.print(i);
		}

		public void print(long l) {
			out.print(l);
		}

		public void print(Object obj) {
			out.print(obj);
		}

		public void print(String s) {
			out.print(s);
		}

		public void print(Object[] obj, String perse) {
			print(obj[0]);
			for (int i = 1;i < obj.length;++ i) {
				print(perse);
				print(obj[i]);
			}
		}

		public void print(Object[][] obj, String perse1, String perse2) {
			print(obj[0], perse1);
			for (int i = 1;i < obj.length;++ i) {
				print(perse2);
				print(obj[i], perse1);
			}
		}

		public void printf(String format, Object... args) {
			out.printf(format, args);
		}

		public void printf(Locale l, String format, Object... args) {
			out.printf(l, format, args);
		}

		public void println() {
			out.println();
		}

		public void println(boolean b) {
			out.println(b);
		}

		public void println(char c) {
			out.println(c);
		}

		public void println(char[] s) {
			out.println(s);
		}

		public void println(double d) {
			out.println(d);
		}

		public void println(double d, int length) {
			print(d, length);
			println();
		}

		public void println(float f) {
			out.println(f);
		}

		public void println(int i) {
			out.println(i);
		}

		public void println(long l) {
			out.println(l);
		}

		public void println(Object obj) {
			out.println(obj);
		}

		public void println(String s) {
			out.println(s);
		}

		public void println(Object[] obj, String perse) {
			print(obj, perse);
			println();
		}

		public void println(Object[][] obj, String perse1, String perse2) {
			print(obj, perse1, perse2);
			println();
		}

		public void flush() {
			out.flush();
			err.flush();
		}
	}

	public enum BoundType {
		CLOSED, OPEN;
	}

	public static class Range<C> implements Serializable{

		private static final long serialVersionUID = -4702828934863023392L;
		protected C lower;
		protected C upper;
		protected BoundType lowerType;
		protected BoundType upperType;
		private Comparator<? super C> comparator;

		protected Range(C lower, BoundType lowerType, C upper, BoundType upperType) {
			this(lower, lowerType, upper, upperType, null);
		}

		protected Range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) {
			this.lower = lower;
			this.upper = upper;
			this.lowerType = lowerType;
			this.upperType = upperType;
			this.comparator = comparator;
		}

		public static <C extends Comparable<? super C>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType) {
			if (lower != null && upper != null) {
				int comp = lower.compareTo(upper);
				if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED);
				else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN))return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED);
			}
			return new Range<C>(lower, lowerType, upper, upperType);
		}

		public static <C> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, Comparator<? super C> comparator) {
			if (lower != null && upper != null) {
				int comp = comparator.compare(lower, upper);
				if (comp > 0) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator);
				else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator);
			}
			return new Range<C>(lower, lowerType, upper, upperType, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> all() {
			return range(null, BoundType.OPEN, null, BoundType.OPEN);
		}

		public static <C> Range<C> all(Comparator<? super C> comparator) {
			return range(null, BoundType.OPEN, null, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> atMost(C upper) {
			return range(null, BoundType.OPEN, upper, BoundType.CLOSED);
		}

		public static <C> Range<C> atMost(C upper, Comparator<? super C> comparator) {
			return range(null, BoundType.OPEN, upper, BoundType.CLOSED, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> lessThan(C upper) {
			return range(null, BoundType.OPEN, upper, BoundType.OPEN);
		}

		public static <C> Range<C> lessThan(C upper, Comparator<? super C> comparator) {
			return range(null, BoundType.OPEN, upper, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> downTo(C upper, BoundType boundType) {
			return range(null, BoundType.OPEN, upper, boundType);
		}

		public static <C> Range<C> downTo(C upper, BoundType boundType, Comparator<? super C> comparator) {
			return range(null, BoundType.OPEN, upper, boundType, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> atLeast(C lower) {
			return range(lower, BoundType.CLOSED, null, BoundType.OPEN);
		}

		public static <C> Range<C> atLeast(C lower, Comparator<? super C> comparator) {
			return range(lower, BoundType.CLOSED, null, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> greaterThan(C lower) {
			return range(lower, BoundType.OPEN, null, BoundType.OPEN);
		}

		public static <C> Range<C> greaterThan(C lower, Comparator<? super C> comparator) {
			return range(lower, BoundType.OPEN, null, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> upTo(C lower, BoundType boundType) {
			return range(lower, boundType, null, BoundType.OPEN);
		}

		public static <C> Range<C> upTo(C lower, BoundType boundType, Comparator<? super C> comparator) {
			return range(lower, boundType, null, BoundType.OPEN, comparator  );
		}

		public static <C extends Comparable<? super C>> Range<C> open(C lower, C upper) {
			return range(lower, BoundType.OPEN, upper, BoundType.OPEN);
		}

		public static <C> Range<C> open(C lower, C upper, Comparator<? super C> comparator) {
			return range(lower, BoundType.OPEN, upper, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> openClosed(C lower, C upper) {
			return range(lower, BoundType.OPEN, upper, BoundType.CLOSED);
		}

		public static <C> Range<C> openClosed(C lower, C upper, Comparator<? super C> comparator) {
			return range(lower, BoundType.OPEN, upper, BoundType.CLOSED, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> closedOpen(C lower, C upper) {
			return range(lower, BoundType.CLOSED, upper, BoundType.OPEN);
		}

		public static <C> Range<C> closedOpen(C lower, C upper, Comparator<? super C> comparator) {
			return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> closed(C lower, C upper) {
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED);
		}

		public static <C> Range<C> closed(C lower, C upper, Comparator<? super C> comparator) {
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> singleton(C value) {
			return range(value, BoundType.CLOSED, value, BoundType.CLOSED);
		}

		public static <C> Range<C> singleton(C value, Comparator<? super C> comparator) {
			return range(value, BoundType.CLOSED, value, BoundType.CLOSED, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> empty() {
			return range(null, BoundType.CLOSED, null, BoundType.CLOSED);
		}

		public static <C> Range<C> empty(Comparator<? super C> comparator) {
			return range(null, BoundType.CLOSED, null, BoundType.CLOSED, comparator);
		}

		public static <C extends Comparable<? super C>> Range<C> encloseAll(Iterable<C> values) {
			C lower = values.iterator().next();
			C upper = lower;
			for (C i : values) {
				if (lower.compareTo(i) > 0) lower = i;
				if (upper.compareTo(i) < 0) upper = i;
			}
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED);
		}

		public static <C> Range<C> encloseAll(Iterable<C> values, Comparator<? super C> comparator) {
			C lower = values.iterator().next();
			C upper = lower;
			for (C i : values) {
				if (comparator.compare(lower, i) > 0) lower = i;
				if (comparator.compare(upper, i) < 0) upper = i;
			}
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, comparator);
		}

		protected int compareLower(C value) {
			return compareLower(value, BoundType.CLOSED);
		}

		protected int compareLower(C value, BoundType boundType) {
			return compareLower(lower, lowerType, value, boundType);
		}

		protected int compareLower(C lower, BoundType lowerType, C value) {
			return compareLower(lower, lowerType, value, BoundType.CLOSED);
		}

		protected int compareLower(C lower, BoundType lowerType, C value, BoundType boundType) {
			if (lower == null) return value == null ? 0 : -1;
			else if (value == null) return 1;
			int compare;
			if (comparator == null) {
				@SuppressWarnings("unchecked")
				Comparable<C> comp = (Comparable<C>)lower;
				compare = comp.compareTo(value);
			} else compare = comparator.compare(lower, value);
			if (compare == 0) {
				if (lowerType == BoundType.CLOSED) -- compare;
				if (boundType == BoundType.CLOSED) ++ compare;
			}
			return compare;
		}

		protected int compareUpper(C value) {
			return compareUpper(value, BoundType.CLOSED);
		}

		protected int compareUpper(C value, BoundType boundType) {
			return compareUpper(upper, upperType, value, boundType);
		}

		protected int compareUpper(C upper, BoundType upperType, C value) {
			return compareUpper(upper, upperType, value, BoundType.CLOSED);
		}

		protected int compareUpper(C upper, BoundType upperType, C value, BoundType boundType) {
			if (upper == null) return value == null ? 0 : 1;
			if (value == null) return -1;
			int compare;
			if (comparator == null) {
				@SuppressWarnings("unchecked")
				Comparable<C> comp = (Comparable<C>)upper;
				compare = comp.compareTo(value);
			} else compare = comparator.compare(upper, value);
			if (compare == 0) {
				if (upperType == BoundType.CLOSED) ++ compare;
				if (boundType == BoundType.CLOSED) -- compare;
			}
			return compare;
		}

		public boolean hasLowerBound() {
			return lower != null;
		}

		public C lowerEndpoint() {
			if (hasLowerBound()) return lower;
			throw new IllegalStateException();
		}

		public BoundType lowerBoundType() {
			if (hasLowerBound()) return lowerType;
			throw new IllegalStateException();
		}

		public boolean hasUpperBound() {
			return upper != null;
		}

		public C upperEndpoint() {
			if (hasUpperBound()) return upper;
			throw new IllegalStateException();
		}

		public BoundType upperBoundType() {
			if (hasUpperBound()) return upperType;
			throw new IllegalStateException();
		}

		/**
		 * この区間が空集合か判定します。
		 * @return 空集合ならばtrue
		 */
		public boolean isEmpty() {
			return lower == null && upper == null && lowerType == BoundType.CLOSED;
		}

		/**
		 * 与えられた引数が区間の左側に位置するか判定します。

		 * 接する場合は区間の左側ではないと判定します。
		 * @param value 調べる引数
		 * @return 区間の左側に位置するならtrue
		 */
		public boolean isLess(C value) {
			return isLess(value, BoundType.CLOSED);
		}

		protected boolean isLess(C value, BoundType boundType) {
			return compareLower(value, boundType) > 0;
		}

		/**
		 * 与えられた引数が区間の右側に位置するか判定します。

		 * 接する場合は区間の右側ではないと判定します。
		 * @param value 調べる引数
		 * @return 区間の右側に位置するならtrue
		 */
		public boolean isGreater(C value) {
			return isGreater(value, BoundType.CLOSED);
		}

		private boolean isGreater(C value, BoundType boundType) {
			return compareUpper(value, boundType) < 0;
		}

		/**
		 * 与えられた引数が区間内に位置するか判定します。

		 * 接する場合も区間内に位置すると判定します。
		 * @param value 調べる引数
		 * @return 区間内に位置するならtrue
		 */
		public boolean contains(C value) {
			return !isLess(value) && !isGreater(value) && !isEmpty();
		}

		/**
		 * 与えられた引数すべてが区間内に位置するか判定します。

		 * 接する場合も区間内に位置すると判定します。
		 * @param value 調べる要素
		 * @return 全ての要素が区間内に位置するならtrue
		 */
		public boolean containsAll(Iterable<? extends C> values) {
			for (C i : values) if (!contains(i)) return false;
			return true;
		}

		/**
		 * 与えられた区間がこの区間に内包されるか判定します。

		 *
		 * @param other
		 * @return 与えられた区間がこの区間に内包されるならtrue
		 */
		public boolean encloses(Range<C> other) {
			return !isLess(other.lower, other.lowerType) && !isGreater(other.upper, other.upperType);
		}

		/**
		 * 与えられた区間がこの区間と公差するか判定します。

		 * 接する場合は公差するものとします。
		 * @param value 調べる引数
		 * @return 区間が交差するならtrue
		 */
		public boolean isConnected(Range<C> other) {
			if (this.isEmpty() || other.isEmpty()) return false;
			C lower, upper;
			BoundType lowerType, upperType;
			if (isLess(other.lower, other.lowerType)) {
				lower = other.lower;
				lowerType = other.lowerType;
			} else {
				lower = this.lower;
				lowerType = this.lowerType;
			}
			if (isGreater(other.upper, other.upperType)) {
				upper = other.upper;
				upperType = other.upperType;
			} else {
				upper = this.upper;
				upperType = this.upperType;
			}
			if (lower == null || upper == null) return true;
			int comp = compareLower(lower, lowerType, upper, upperType);
			return comp <= 0;
		}
		/**
		 * この区間との積集合を返します。
		 * @param connectedRange 積集合を求める区間
		 * @return 積集合
		 */
		public Range<C> intersection(Range<C> connectedRange) {
			if (this.isEmpty() || connectedRange.isEmpty()) {
				if (comparator == null) return new Range<C>(null, BoundType.CLOSED, null, BoundType.CLOSED);
				return empty(comparator);
			}
			C lower, upper;
			BoundType lowerType, upperType;
			if (isLess(connectedRange.lower, connectedRange.lowerType)) {
				lower = connectedRange.lower;
				lowerType = connectedRange.lowerType;
			} else {
				lower = this.lower;
				lowerType = this.lowerType;
			}
			if (isGreater(connectedRange.upper, connectedRange.upperType)) {
				upper = connectedRange.upper;
				upperType = connectedRange.upperType;
			} else {
				upper = this.upper;
				upperType = this.upperType;
			}
			if (comparator == null) {
				return new Range<C>(lower, lowerType, upper, upperType);
			}
			return range(lower, lowerType, upper, upperType, comparator);
		}

		/**
		 * この区間との和集合を返します。
		 * @param other 和集合を求める区間
		 * @return 和集合
		 */
		public Range<C> span(Range<C> other) {
			if (other.isEmpty()) return new Range<C>(lower, lowerType, upper, upperType);
			C lower, upper;
			BoundType lowerType, upperType;
			if (isLess(other.lower, other.lowerType)) {
				lower = this.lower;
				lowerType = this.lowerType;
			} else {
				lower = other.lower;
				lowerType = other.lowerType;
			}
			if (isGreater(other.upper, other.upperType)) {
				upper = this.upper;
				upperType = this.upperType;
			} else {
				upper = other.upper;
				upperType = other.upperType;
			}
			return new Range<C>(lower, lowerType, upper, upperType, comparator);
		}

		@Override
		public boolean equals(Object object) {
			if (this == object) return true;
			if (object instanceof Range) {
				@SuppressWarnings("unchecked")
				Range<C> comp = (Range<C>) object;
				return compareLower(comp.lower, comp.lowerType) == 0 && compareUpper(comp.upper, comp.upperType) == 0 && lowerType == comp.lowerType && upperType == comp.upperType;
			}
			return false;
		}

		@Override
		public int hashCode() {
			if (lower == null && upper == null) return 0;
			else if (lower == null) return upper.hashCode();
			else if (upper == null) return lower.hashCode();
			return lower.hashCode() ^ upper.hashCode();
		}

		@Override
		public String toString() {
			if (isEmpty()) return "()";
			return (lowerType == BoundType.OPEN ? "(" : "[") + (lower == null ? "" : lower.toString()) + ".." + (upper == null ? "" : upper.toString()) + (upperType == BoundType.OPEN ? ")" : "]");
		}
	}

	public interface IterableFunction<T> {
		public T next(T value);
	}

	public static class IterableRange<C> extends Range<C> implements Iterable<C>{

		private static final long serialVersionUID = 9065915259748260688L;
		protected IterableFunction<C> func;

		protected IterableRange(C lower, BoundType lowerType, C upper, BoundType upperType, IterableFunction<C> func) {
			super(lower, lowerType, upper, upperType);
			this.func = func;
		}

		public static <C extends Comparable<? super C>> IterableRange<C> range(C lower, BoundType lowerType, C upper, BoundType upperType, IterableFunction<C> func) {
			if (lower == null || upper == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func);
			int comp = lower.compareTo(upper);
			if (comp > 0) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func);
			else if (comp == 0 && (lowerType == BoundType.OPEN || upperType == BoundType.OPEN)) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func);
			return new IterableRange<C>(lower, lowerType, upper, upperType, func);
		}

		public static <C extends Comparable<? super C>> IterableRange<C> open(C lower, C upper, IterableFunction<C> func) {
			if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func);
			return range(func.next(lower), BoundType.CLOSED, upper, BoundType.OPEN, func);
		}

		public static <C extends Comparable<? super C>> IterableRange<C> openClosed(C lower, C upper, IterableFunction<C> func) {
			if (lower == null) return new IterableRange<C>(null, BoundType.CLOSED, null, BoundType.CLOSED, func);
			return range(func.next(lower), BoundType.CLOSED, upper, BoundType.CLOSED, func);
		}

		public static <C extends Comparable<? super C>> IterableRange<C> closedOpen(C lower, C upper, IterableFunction<C> func) {
			return range(lower, BoundType.CLOSED, upper, BoundType.OPEN, func);
		}

		public static <C extends Comparable<? super C>> IterableRange<C> closed(C lower, C upper, IterableFunction<C> func) {
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED, func);
		}

		public static <C extends Comparable<? super C>> IterableRange<C> singleton(C value, IterableFunction<C> func) {
			return range(value, BoundType.CLOSED, value, BoundType.CLOSED, func);
		}
		private class Iter implements Iterator<C> {
			C now;
			Iter() {
				now = lower;
			}
			@Override
			public final boolean hasNext() {
				return !isGreater(now);
			}

			@Override
			public final C next() {
				C ret = now;
				now = func.next(now);
				return ret;
			}

			@Override
			public final void remove() {
				throw new UnsupportedOperationException();
			}
		}

		@Override
		public Iterator<C> iterator() {
			return new Iter();
		}

		public int getDistance() {
			C check = upper;
			int ret = 0;
			while (lower != check) {
				check = func.next(check);
				++ ret;
			}
			return ret;
		}
	}

	public static class IntRange extends IterableRange<Integer>{

		private static final long serialVersionUID = 8177932312110314067L;

		private static class Next implements IterableFunction<Integer> {

			@Override
			public Integer next(Integer value) {
				return value + 1;
			}
		}

		protected IntRange() {
			super(null, BoundType.CLOSED, null, BoundType.CLOSED, new Next());
		}

		protected IntRange(int lower, BoundType lowerType, int upper, BoundType upperType) {
			super(lower, lowerType, upper, upperType, new Next());
		}

		public static IntRange range(int lower, BoundType lowerType, int upper, BoundType upperType) {
			if (lower > upper) return new IntRange();
			if (lowerType == BoundType.OPEN) ++ lower;
			if (upperType == BoundType.OPEN) -- upper;
			return new IntRange(lower, BoundType.CLOSED, upper, BoundType.CLOSED);
		}

		public static IntRange open(int lower, int upper) {
			return range(lower, BoundType.OPEN, upper, BoundType.OPEN);
		}

		public static IntRange open(int upper) {
			return range(0, BoundType.CLOSED, upper, BoundType.OPEN);
		}

		public static IntRange openClosed(int lower, int upper) {
			return range(lower, BoundType.OPEN, upper, BoundType.CLOSED);
		}

		public static IntRange closedOpen(int lower, int upper) {
			return range(lower, BoundType.CLOSED, upper, BoundType.OPEN);
		}

		public static IntRange closed(int lower, int upper) {
			return range(lower, BoundType.CLOSED, upper, BoundType.CLOSED);
		}

		public static IntRange closed(int upper) {
			return range(0, BoundType.CLOSED, upper, BoundType.CLOSED);
		}

		public static IntRange singleton(int value) {
			return range(value, BoundType.CLOSED, value, BoundType.CLOSED);
		}

		private class Iter implements Iterator<Integer> {
			int now;
			public Iter() {
				now = lower;
			}
			@Override
			public final boolean hasNext() {
				return now <= upper;
			}

			@Override
			public final Integer next() {
				return now++;
			}

			@Override
			public final void remove() {
				throw new UnsupportedOperationException();
			}
		}

		@Override
		public Iterator<Integer> iterator() {
			return new Iter();
		}

		@Override
		public int getDistance() {
			int ret = upper - lower;
			if (upperType == BoundType.CLOSED) ++ ret;
			return ret;
		}

		public int getClosedLower() {
			return lower;
		}

		public int getOpenLower() {
			return lower - 1;
		}

		public int getClosedUpper() {
			return upperType == BoundType.CLOSED ? upper : upper - 1;
		}

		public int getOpenUpper() {
			return upperType == BoundType.CLOSED ? upper + 1 : upper;
		}
	}

	public interface Ring<T> {
		public T add(T left, T right);
		public T addUnit();
		public T addInverse(T element);
		public T multiply(T left, T right);
		public T multiplyUnit();
		public T multiplyInverse(T element);
	}

	public class ModInteger extends Number implements Ring<ModInteger>{

		private static final long serialVersionUID = -8595710127161317579L;
		private final int mod;
		private int num;

		public ModInteger(int mod) {
			this.mod = mod;
			num = 0;
		}

		public ModInteger(int mod, int num) {
			this.mod = mod;
			this.num = validNum(num);
		}

		public ModInteger(ModInteger n) {
			mod = n.mod;
			num = n.num;
		}

		private ModInteger(ModInteger n, int num) {
			mod = n.mod;
			this.num = num;
		}

		private int validNum(int n) {
			n %= mod;
			if (n < 0) n += mod;
			return n;
		}

		protected int inverse(int n) {
			 int m = mod, u = 0, v = 1, t;
			 while(n != 0) {
				 t = m / n;
				 m -= t * n;
				 u -= t * v;
				 if (m != 0) {
					 t = n / m;
					 n -= t * m;
					 v -= t * u;
				 } else {
					 v %= mod;
					 if (v < 0) v += mod;
					 return v;
				 }
			 }
			 u %= mod;
			 if (u < 0) u += mod;
			 return u;
		}

		public boolean isPrime(int n) {
			if ((n & 1) == 0) return false; // 偶数
			for (int i = 3, j = 8, k = 9;k <= n;i += 2, k += j += 8) if (n % i == 0) return false;
			return true;
		}

		@Override
		public int intValue() {
			return num;
		}

		@Override
		public long longValue() {
			return num;
		}

		@Override
		public float floatValue() {
			return num;
		}

		@Override
		public double doubleValue() {
			return num;
		}

		public ModInteger add(int n) {
			return new ModInteger(this).addEqual(n);
		}

		public ModInteger add(ModInteger n) {
			return new ModInteger(this).addEqual(n);
		}

		public ModInteger addEqual(int n) {
			num = validNum(num + n);
			return this;
		}

		public ModInteger addEqual(ModInteger n) {
			if ((num += n.num) >= mod) num -= mod;
			return this;
		}

		public ModInteger subtract(int n) {
			return new ModInteger(this).subtractEqual(n);
		}

		public ModInteger subtract(ModInteger n) {
			return new ModInteger(this).subtractEqual(n);
		}

		public ModInteger subtractEqual(int n) {
			num = validNum(num - n);
			return this;
		}

		public ModInteger subtractEqual(ModInteger n) {
			if ((num -= n.num) < 0) num += mod;
			return this;
		}

		@Override
		public ModInteger add(ModInteger left, ModInteger right) {
			return new ModInteger(left).addEqual(right);
		}

		@Override
		public ModInteger addUnit() {
			return new ModInteger(mod, 0);
		}

		@Override
		public ModInteger addInverse(ModInteger element) {
			return new ModInteger(element, element.mod - element.num);
		}

		public ModInteger multiply(int n) {
			return new ModInteger(this).multiplyEqual(n);
		}

		public ModInteger multiply(ModInteger n) {
			return new ModInteger(this).multiplyEqual(n);
		}

		public ModInteger multiplyEqual(int n) {
			num = (int)((long)num * n % mod);
			if (num < 0) num += mod;
			return this;
		}

		public ModInteger multiplyEqual(ModInteger n) {
			num = (int)((long)num * n.num % mod);
			return this;
		}

		public ModInteger divide(int n) {
			return new ModInteger(this).divideEqual(n);
		}

		public ModInteger divide(ModInteger n) {
			return new ModInteger(this).divideEqual(n);
		}

		public ModInteger divideEqual(int n) {
			num = (int)((long)num * inverse(validNum(n)) % mod);
			return this;
		}

		public ModInteger divideEqual(ModInteger n) {
			num = (int)((long)num * n.inverse(n.num) % mod);
			return this;
		}

		@Override
		public ModInteger multiply(ModInteger left, ModInteger right) {
			return new ModInteger(left).multiplyEqual(right);
		}

		@Override
		public ModInteger multiplyUnit() {
			return new ModInteger(this, 1);
		}

		@Override
		public ModInteger multiplyInverse(ModInteger element) {
			return new ModInteger(element, element.inverse(element.num));
		}

		public ModInteger pow(int n) {
			return new ModInteger(this).powEqual(n);
		}

		public ModInteger pow(ModInteger n) {
			return new ModInteger(this).powEqual(n);
		}

		public ModInteger powEqual(int n) {
			long ans = 1, num = this.num;
			if (n < 0) {
				n = -n;
				while (n != 0) {
					if ((n & 1) != 0) ans = ans * num % mod;
					n >>>= 1;
					num = num * num % mod;
				}
				this.num = inverse((int)ans);
				return this;
			}
			while (n != 0) {
				if ((n & 1) != 0) ans = ans * num % mod;
				n >>>= 1;
				num = num * num % mod;
			}
			this.num = (int)ans;
			return this;
		}

		public ModInteger powEqual(ModInteger n) {
			long num = this.num;
			this.num = 1;
			int mul = n.num;
			while (mul != 0) {
				if ((mul & 1) != 0) this.num *= num;
				mul >>>= 1;
				num *= num;
				num %= mod;
			}
			return this;
		}

		public ModInteger equal(int n) {
			num = validNum(n);
			return this;
		}

		public ModInteger equal(ModInteger n) {
			num = n.num;
			return this;
		}

		public int toInt() {
			return num;
		}

		public int getMod() {
			return mod;
		}

		@Override
		public boolean equals(Object x) {
			if (x instanceof ModInteger) return ((ModInteger)x).num == num && ((ModInteger)x).mod == mod;
			return false;
		}

		@Override
		public int hashCode() {
			return num ^ mod;
		}

		@Override
		public String toString() {
			return String.valueOf(num);
		}

		@Deprecated
		public String debug() {
			int min = num, ans = 1;
			for (int i = 2;i < min;++ i) {
				int tmp = divide(i).num;
				if (min > tmp) {
					min = tmp;
					ans = i;
				}
			}
			return min + "/" + ans;
		}
	}

	/**
	 * 素数を法とする演算上で、組み合わせの計算を高速に行います。
	 * @author 31536000
	 *
	 */
	public class ModUtility {
		private final int mod, totient;
		private int[] fact, inv, invfact;
		/**
		 * modを法とする
		 * @param mod
		 */
		public ModUtility(int mod) {
			this(mod, 2);
		}

		public ModUtility(int mod, int calc) {
			if (mod <= 0) throw new IllegalArgumentException("illegal mod: " + mod);
			this.mod = mod;
			int totient = mod;
			for (int i = 2;i * i <= mod;++ i) {
				if (mod % i == 0) {
					totient = totient / i * (i - 1);
					while ((mod %= i) % i == 0);
				}
			}
			this.totient = totient;
			precalc(calc);
		}

		public void precalc(int calc) {
			if (calc < 2) calc = 2;
			fact = new int[calc];
			inv = new int[calc];
			invfact = new int[calc];
			fact[0] = invfact[0] = fact[1] = invfact[1] = inv[1] = 1;
			for (int i = 2;i < calc;++ i) {
				fact[i] = (int)((long)fact[i - 1] * i % mod);
				inv[i] = (int)(mod - (long)inv[mod % i] * (mod / i) % mod);
				invfact[i] = (int)((long)invfact[i - 1] * inv[i] % mod);
			}
		}

		public ModInteger create() {
			return create(0);
		}

		public ModInteger create(int n) {
			return new ModInt(n);
		}

		private class ModInt extends ModInteger {

			private static final long serialVersionUID = -2435281861935422575L;

			public ModInt(int n) {
				super(mod, n);
			}

			@Override
			protected int inverse(int n) {
				return ModInt.this.inverse(n);
			}
		}

		public int inverse(int n) {
			try {
				if (inv.length > n) return inv[n];
				 int m = mod, u = 0, v = 1, t;
				 while(n != 0) {
					 t = m / n;
					 m -= t * n;
					 u -= t * v;
					 if (m != 0) {
						 t = n / m;
						 n -= t * m;
						 v -= t * u;
					 } else {
						 v %= mod;
						 if (v < 0) v += mod;
						 return v;
					 }
				 }
				 u %= mod;
				 if (u < 0) u += mod;
				 return u;
			} catch (ArrayIndexOutOfBoundsException e) {
				throw new IllegalArgumentException();
			}
		}

		public int factorial(int n) {
			try {
				if (fact.length > n) return fact[n];
				long ret = fact[fact.length - 1];
				for (int i = fact.length;i <= n;++ i) ret = ret * i % mod;
				return (int)ret;
			} catch (ArrayIndexOutOfBoundsException e) {
				throw new IllegalArgumentException();
			}
		}

		public int permutation(int n, int k) {
			if (k < 0) throw new IllegalArgumentException();
			if (n < k) return 0;
			if (fact.length > n) return (int)((long)fact[n] * invfact[n - k] % mod);
			long ret = 1;
			for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod;
			return (int)ret;
		}

		public int combination(int n, int k) {
			if (k < 0) throw new IllegalArgumentException();
			if (n < k) return 0;
			if (fact.length > n) return (int)((long)fact[n] * invfact[k] % mod * invfact[n - k] % mod);
			long ret = 1;
			if (n < 2 * k) k = n - k;
			if (invfact.length > k) ret = invfact[k];
			else ret = inverse(factorial(k));
			for (int i = n - k + 1;i <= n;++ i) ret = ret * i % mod;
			return (int)ret;
		}

		public int multinomial(int n, int... k) {
			int sum = 0;
			for (int i : k) sum += i;
			long ret = factorial(n);
			if (fact.length > n) {
				for (int i : k) {
					if (i < 0) throw new IllegalArgumentException();
					ret = ret * invfact[i] % mod;
					sum += i;
				}
				if (sum > n) return 0;
				ret = ret * invfact[n - sum] % mod;
			} else {
				for (int i : k) {
					if (i < 0) throw new IllegalArgumentException();
					if (invfact.length > i) ret = ret * invfact[i] % mod;
					else ret = ret * inverse(factorial(i)) % mod;
					sum += i;
				}
				if (sum > n) return 0;
				if (invfact.length > n - sum) ret = ret * invfact[n - sum] % mod;
				else ret = ret * inverse(factorial(n - sum)) % mod;
			}
			return (int)ret;
		}

		public int multichoose(int n, int k) {
			return combination(n + k - 1, k);
		}

		public int pow(int n, int m) {
			long ans = 1, num = n;
			if (m < 0) {
				m = -m;
				while (m != 0) {
					if ((m & 1) != 0) ans = ans * num % mod;
					m >>>= 1;
					num = num * num % mod;
				}
				return inverse((int)ans);
			}
			while (m != 0) {
				if ((m & 1) != 0) ans = ans * num % mod;
				m >>>= 1;
				num = num * num % mod;
			}
			return (int)ans;
		}

		public int totient() {
			return totient;
		}

		public boolean isPrime() {
			return totient == mod - 1;
		}

		public int mod(int n) {
			return (n %= mod) < 0 ? n + mod : n;
		}

		public int add(int n, int m) {
			return mod(n + m);
		}

		public int subtract(int n, int m) {
			return mod(n - m);
		}

		public int multiply(int n, int m) {
			int ans = (int)((long)n * m % mod);
			return ans < 0 ? ans + mod : ans;
		}

		public int divide(int n, int m) {
			return multiply(n, inverse(m));
		}
	}
}


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
	public static void main(String[] args) throws Exception {

		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		String line = reader.readLine();
		String[] str = line.split(" ");
		int N = Integer.parseInt(str[0]);
		int A = Integer.parseInt(str[1]);
		int B = Integer.parseInt(str[2]);

		if (N * A <= B) {
			System.out.println(N*A);
		}
		else {
			System.out.println(B);
		}
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		String[] NAB = br.readLine().split(" ");

		int N = Integer.parseInt(NAB[0]);
		int A = Integer.parseInt(NAB[1]);
		int B = Integer.parseInt(NAB[2]);

		if (N * A > B) {
			System.out.println(B);
		}
		if (N * A < B) {
			System.out.println(N * A);
		}
		if (N * A == B) {
			System.out.println(B);
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int k= 1;
        HashMap<String,Integer> hashMap = new HashMap<>();
        hashMap.put("SUN",7);
        hashMap.put("MON",6);
        hashMap.put("TUE",5);
        hashMap.put("WED",4);
        hashMap.put("THU",3);
        hashMap.put("FRI",2);
        hashMap.put("SAT",1);
        String s1;
        String s2;
        int a,b,c;
        double n;
        while(k-->0){
            c=s.nextInt();
            a=s.nextInt();
            b=s.nextInt();
            System.out.println(Math.min(a,b)*c);
        }
    }

    private static int binary_search(
            int arr[], int l,
            int h, int x)
    {
        while (l <= h) {
            int mid = (l + h) / 2;
            if (arr[mid] <= x)
                l = mid + 1;
            else
                h = mid - 1;
        }
        return h;
    }
    static int gcd(int a, int b)
    {
        if(b==0) {
            return a;
        }
        return gcd(b,a%b);
    }
    private static boolean isPrime(int n) {
        if (n == 2)
            return true;
        else if ((n % 2 == 0 && n > 2) || n < 2)
            return false;
        else {
            for (int i = 3; i <= (int) Math.sqrt(n); i += 2) {
                if (n % i == 0)
                    return false;
            }
            return true;
        }

    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }

        long nextLong() {
            return Long.parseLong(next());
        }

        double nextDouble() {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt(),a = s.nextInt(),b=s.nextInt();

        System.out.println(Math.min(n*a,n*b));
    }

}

class Scanner
{
    StringTokenizer st;
    BufferedReader br;

    public Scanner(InputStream s){	br = new BufferedReader(new InputStreamReader(s));}

    public String next() throws IOException
    {
        while (st == null || !st.hasMoreTokens())
            st = new StringTokenizer(br.readLine());
        return st.nextToken();
    }

    public int nextInt() throws IOException {return Integer.parseInt(next());}

    public long nextLong() throws IOException {return Long.parseLong(next());}

    public String nextLine() throws IOException {return br.readLine();}

    public double nextDouble() throws IOException
    {
        String x = next();
        StringBuilder sb = new StringBuilder("0");
        double res = 0, f = 1;
        boolean dec = false, neg = false;
        int start = 0;
        if(x.charAt(0) == '-')
        {
            neg = true;
            start++;
        }
        for(int i = start; i < x.length(); i++)
            if(x.charAt(i) == '.')
            {
                res = Long.parseLong(sb.toString());
                sb = new StringBuilder("0");
                dec = true;
            }
            else
            {
                sb.append(x.charAt(i));
                if(dec)
                    f *= 10;
            }
        res += Long.parseLong(sb.toString()) / f;
        return res * (neg?-1:1);
    }

    public boolean ready() throws IOException {return br.ready();}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int A = sc.nextInt();
		int B = sc.nextInt();

		if (N*A >= B) {
			System.out.println(N*A);
		} else {
			System.out.println(B);
		}

	}
}


// Written By NewbieChd
#include <cstdio>
#include <cctype>
#include <algorithm>
using namespace std;

const int BUF = 1000000;
char buf[BUF], *p1, *p2;
inline char getChar() { return p1 == p2 && (p2 = (p1 = buf) + fread(buf, 1, BUF, stdin), p1 == p2) ? EOF : *p1++; }
inline int read() {
    register int f = 0;
    bool b = 1;
    char c;
    while (!isdigit(c = getChar()))
        if (c == 45)
            b = 0;
    do
        f = f * 10 + (c ^ 48);
    while (isdigit(c = getChar()));
    return b ? f : ~f + 1;
}

const int maxN = 100003;

int main() {
    int a = read(), b = read(), c = read();
    printf("%d\n", min(a * b, c));
    return 0;
}


#include<stdio.h>
int main()
{
	int a,b,c,t;
	scanf("%d%d%d",&a,&b,&c);
	if(a*b>c)
	t=c;
	else
	t=a*b;
	printf("%d",t);
 }


#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

int n,a,b;

int read(){
	int t=1,s=0;
	char c=getchar();
	while((c>'9'||c<'0')&&c!='-')c=getchar();
	if(c=='-')t=-1,c=getchar();
	while(c>='0'&&c<='9')
	s=s*10+c-'0',c=getchar();
	return s*t;
}

int main(void){
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	scanf("%d %d %d",&n,&a,&b);
	int ans=min(n*a,b);
	printf("%d",ans);
}


#include <iostream>

int main() {
  int n, a, b; std::cin >> n >> a >> b;
  int ans = (n*a > b ? : b : n*a);
  std::cout << ans << std::endl;

  return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;

int main()
{
    long l, r;
    cin >> l >> r;

    if (r - l >= 2018)
        cout << '0';
    else
    {
        int lmod = l % 2019;
        int rmod = r % 2019;
        if (lmod >= rmod)
            cout << '0';
        else
        {
            long ans = lmod * (lmod + 1);
            cout << ans << endl;
        }
    }
}


#include<iostream>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<cmath>
#include<map>

using namespace std;

#define rep(i,N) for(int i=0;i<N;i++) //0から

typedef long long ll;

ll binary_search(vector<ll> a, ll n, ll key){
    ll right = n, left = -1;
    ll md = (right + left) / 2;

    while(right - left > 1){
        if(a[md] <= key){
            right = md;
        }else{
            left = md;
        }
        md = (right + left) / 2;
    }
    if(left == -1) return -1; //無い場合
    return right;
}

vector<ll> prime;
void Prime(ll n){ //線形篩,素数列挙
    vector<ll> p(n,0);
    p[0]=1;
    p[1]=1;
    for(ll i=2;i<n;i++){
        if(p[i]==0){
            prime.push_back(i);
            p[i]=i;
        }
        ll k=prime.size();
        for(ll j=0;j<k && i*prime[j]<n && prime[j]<=p[i];j++){
            p[i*prime[j]]=prime[j];
        }
    }
}

ll gcd(ll a,ll b){
    if(a<b){
        swap(a,b);
    }
    //a>=b
    ll r=a%b;
    while(r!=0){
        a=b;
        b=r;
        r=a%b;
    }
    return b;
}

#define MOD ((ll)1e+9 + 7)

//cout<<fixed<<setprecision(10);
int main(){
    int n,a,b;
    cout<<min(n*a,b)<<endl;

    return 0;
}


#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
    int n,a,b;
    scanf("%d %d %d",&n,&a,&b);
    if(a*n<b)printf("%d",n*a);
    else printf("%d",b);
    return 0;
}


#include <stdio.h>
int main(void){
   int n,a,b;
   scanf("%d%d%d",&n,&a,&b);
   if(a*n>b){
       printf("%d",b);
   }else{
       printf("%d",a*n);
   }
    return 0;
}


#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    int n, a, b;
    bool result = false;
    do{
        scanf("%d", &n);
        scanf("%d", &a);
        scanf("%d", &b);
        if((1 <= n && n <= 20) && (1 <= a && a <= 50) && (1 <= b && b <= 50)){
            result = true;
        }
    }while(result == false);

    int na = n * a;
    if (na <= b){
        printf("%d\n", na);
    }else{
        printf("%d\n", b);
    }
    return 0;
}


#include<stdio.h>

int main(){
	int n,d,i,j,sum = 0,num = 0;
	int x[100][100];
	scanf("%d %d",&n,&d);
	for(i = 0; i < n; i++){
		for(j = 0; j < d; j++){
			scanf("%d",&x[i][j]);
		}
	}

	for(int k = 0; k < n; k++){
	for(i = k + 1; i < n; i++){
		for(j = 0; j < d; j++){
			sum += (x[i][j] - x[k][j]) * (x[i][j] - x[k][j]);
			printf("%d\n",sum);
		}
	    for(j = 0; j <= sum; j++){
			if(sum == j * j){
				num += 1;
			}
	    }
		sum = 0;
	}
	}
	printf("%d",num);
}


#include<stdio.h>
int main(){
  int a,b,c;
  scanf("%d%d%d" &a,&b,&c);

  int d=a*b;

  int e=min({d,c});
  printf("%d", e);
  return 0;
}


function main(input){
  input = input.split("\n");
  var n = parseInt(input[0].split(" ")[0]);
  var a = parseInt(input[0].split(" ")[1]);
  var b = parseInt(input[0].split(" ")[2]);

  console.log(n*a > b ? b : n*a);
}

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


function Main(input) {
    input = input.trim()
  input = input.split(" ").map(Number);
  console.log(Math.min(input[0]*input[1],input[2]))
}Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input){
var all = input.split(" ");
var N = parseInt(all[0],10);
var A = parseInt(all[1],10);
var B = parseInt(all[2],10);

var na = A*N;
if(na>B){
    console.log(B);
}else{
    console.log(na);
}

}

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


"use strict"

var inputs = '';
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
})

reader.on('line', function(input) {
  inputs = input
})

reader.on('close', function() {
  let items = inputs.trim().split(' ')
  let n = parseInt(items[0])
  let a = parseInt(items[1])
  let b = parseInt(items[2])
  let train = n * a
  let taxi = b
  if(train < taxi){
    console.log(train)
    process.exit(1)
  }
  console.log(taxi)
  process.exit(1)
})