import java.util.Queue;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int h = sc.nextInt();
        int w = sc.nextInt();

        int map[][] = new int[h + 2][w + 2];
        Queue<Pos> queue = new ArrayDeque<Pos>();
        for (int i = 0; i < h; i++) {
            String s = sc.next();
            for (int j = 0; j < w; j++) {
                char c = s.charAt(j);
                if (c == '#') {
                    queue.add(new Pos(i + 1, j + 1));
                    map[i + 1][j + 1] = 1;
                }
            }
        }
        Arrays.fill(map[0], -1);
        Arrays.fill(map[h + 1], -1);
        for (int i = 0; i < h + 1; i++) {
            map[i][0] = -1;
            map[i][w + 1] = -1;
        }
        int max = 0;
        while (!queue.isEmpty()) {
            Pos p = queue.poll();
            int dx[] = { 0, 1, 0, -1 };
            int dy[] = { -1, 0, 1, 0 };
            for (int i = 0; i < 4; i++) {
                int ni = p.i + dx[i];
                int nj = p.j + dy[i];
                if (map[ni][nj] == 0) {
                    map[ni][nj] = map[p.i][p.j] + 1;
                    max = Math.max(max, map[ni][nj]);
                    queue.add((new Pos(ni, nj)));
                }
            }
        }

        System.out.println(max - 1);

        sc.close();
    }
}

class Pos {
    int i, j;

    Pos(int i, int j) {
        this.i = i;
        this.j = j;
    }
}


import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

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

	void solve() {
		Scanner sc =  new Scanner(System.in);

		//上下左右
		int[] dx = {1, 0, -1, 0};
		int[] dy = {0, 1, 0, -1};

		int H = sc.nextInt();
		int W = sc.nextInt();
		System.out.println(H +" " + W);

		char[][] charMap = new char[H][W];
		boolean[][] map = new boolean[H][W];

		Queue<Place> que = new ArrayDeque<Place>();

		// 入力文字列の抽出
		for (int i = 0; i < H; i++) {
			String s =  sc.next();
			System.out.println(s);
			charMap[i] = s.toCharArray();
			for (int j = 0; j < W; j++) {
				if (charMap[i][j] == '#') {
					que.add(new Place(i, j, 0));
					map[i][j] = true;
				}
			}
		}
		int max = 0;
		while (que.size() != 0){
			Place place = que.remove();

			for (int i = 0; i < 4; i++) {
				int x = place.getX() + dx[i];
				int y = place.getY() + dy[i];
				if (x < 0 || x >= H || y < 0 || y >= W) {
					continue;
				}
				if (! map[x][y]) {
					que.add(new Place(x,y, place.getCount() + 1));
					map[x][y] = true;
					max = place.getCount() + 1;
				}
			}
		}
		System.out.println(max);
	}

	// 場所を記憶
	class Place {
		private int x;
		private int y;
		private int count;

		public Place(int x, int y, int count) {
			this.x = x;
			this.y = y;
			this.count = count;
		}
		public int getX() {
			return this.x;
		}

		public int getY() {
			return this.y;
		}
		public int getCount() {
			return this.count;
		}
	}
}

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

Score : 300 points

Problem Statement

You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black.
HW characters from A_{11} to A_{HW} represent the colors of the squares.
A_{ij} is # if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is . if that square is white.

We will repeatedly perform the following operation until all the squares are black:

Every white square that shares a side with a black square, becomes black.

Find the number of operations that will be performed.
The initial grid has at least one black square.

Constraints

1 \leq H,W \leq 1000

A_{ij} is # or ..

The given grid has at least one black square.

Input

Input is given from Standard Input in the following format:

H W
A_{11}A_{12}...A_{1W}
:
A_{H1}A_{H2}...A_{HW}

Output

Print the number of operations that will be performed.

Sample Input 1

3 3
...
.#.
...

Sample Output 1

2

After one operation, all but the corners of the grid will be black. After one more operation, all the squares will be black.

Sample Input 2

6 6
..#..#
......
#..#..
......
.#....
....#.

Sample Output 2

3

Submitted source-code file size, in bytes.

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

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


import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

	static final int INF = 9999999;
	static int h;
	static int w;
	static int[][] table;
	static Queue<int[]> sq;

	public static void main(String... args) {

		try (Scanner sc = new Scanner(System.in)) {
			String[] tmp = sc.nextLine().split(" ");
			h = Integer.parseInt(tmp[0]);
			w = Integer.parseInt(tmp[1]);

			table = new int[h][w];

			IntStream.range(0, h).forEach(y -> {
				String s = sc.nextLine();
				IntStream.range(0, w).forEach(x -> {
					table[y][x] = s.charAt(x) == '#' ? 0 : INF;
				});
			});

		}
		sq = new ArrayDeque<>(h * w);

		IntStream.range(0, h).forEach(y -> {
			IntStream.range(0, w).forEach(x -> {
				if (table[y][x] == 0) {
					sq.add(new int[] { y, x, 0 });
				}
			});
		});

		while (!sq.isEmpty()) {
			int[] b = sq.remove();
			erosion(b[0], b[1], b[2]);
		}

		int maxDis = Arrays.stream(table)
			.map(row -> Arrays.stream(row))
			.mapToInt(rs -> rs.reduce(0, (a,b) -> Math.max(a, b)))
			.reduce(0, (a,b) -> Math.max(a, b));

		System.out.println(maxDis);
	}

	static void erosion(int y, int x, int n) {
		if (n < table[y][x] || n == 0) {
			table[y][x] = n;

			if (y < h - 1) {
				sq.add(new int[] { y + 1, x, n + 1 });
			}
			if (y > 0) {
				sq.add(new int[] { y - 1, x, n + 1 });
			}
			if (x < w - 1) {
				sq.add(new int[] { y, x + 1, n + 1 });
			}
			if (x > 0) {
				sq.add(new int[] { y, x - 1, n + 1 });
			}
		}
	}
}


import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Main  implements Runnable { //Runnableを実装する

    public static void main(String[] args) {

        new Thread(null, new Main(), "", 16 * 1024 * 1024).start(); //16MBスタックを確保して実行

    }

    public void run() {
		Scanner sc = new Scanner(System.in);
		//Scanner sc = new Scanner("3 3 ... .#. ...");
		int h = Integer.parseInt(sc.next());
		int w = Integer.parseInt(sc.next());
		//int b = Integer.parseInt(sc.next());
		//int t = Integer.parseInt(sc.next());
		//int k = 0;
		//int k = Integer.parseInt(sc.next());
		//String str = sc.next();
		//char c[] = str.toCharArray();
		char a[][] = new char[h][w];
		char anext[][] = new char[h][w];
		int atmp[] = new int[h];
		int max= 0;
		for (int i = 0; i < h; i++)
		{
				a[i]= sc.next().toCharArray();
		}
		for(int k = 0; k < 2000; k++)
		{
		    for (int i=0; i < h; i++) {
		        System.arraycopy(a[i], 0, anext[i], 0, w);
		    }
		    int hap = 0;
			for (int i = 0; i < h; i++)
			{
				for (int j = 0; j < w; j++)
				{
					if(a[i][j] == '.')
					{
						if(i-1>=0)
						{
							if (a[i-1][j] == '#')
							{
								anext[i][j] = '#';
								hap=1;
							}
						}
						if(j-1>=0)
						{
							if (a[i][j-1] == '#')
							{
								anext[i][j] = '#';
								hap=1;
							}
						}
						if(i+1<h)
						{
							if (a[i+1][j] == '#')
							{
								anext[i][j] = '#';
								hap=1;
							}
						}
						if(j+1<w)
						{
							if (a[i][j+1] == '#')
							{
								anext[i][j] = '#';
								hap=1;
							}
						}
					}
				}
			}
			if(hap ==1)
			{
				max++;
			}
		    for (int i=0; i < h; i++) {
		        System.arraycopy(anext[i], 0, a[i], 0, w);
		    }

		}

		int ans = max;
		PrintWriter out = new PrintWriter(System.out);
		out.println(ans);
		out.flush();
	}
    private static int gcd(int m, int n) {
        if(m < n)
        {
        	return gcd(n, m);
        }
        if(n==0)
        {
        	return m;
        }
        return gcd(n, m % n);
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int H = sc.nextInt();
        int W = sc.nextInt();
        String[][] A = new String[H][W];
        String[][] R = new String[H][W];
        for (int i=0; i<H; i++) {
            String row = sc.next();
            for (int k=0; k<row.length(); k++) {
                A[i][k] = String.valueOf(row.charAt(k));
                R[i][k] = String.valueOf(row.charAt(k));
            }
        }
        int loop = 0;
        while (true) {
            loop++;
            int fill = 0;
            for (int i=0; i<H; i++) {
                for (int j = 0; j < W; j++) {
                    A[i][j] = R[i][j];
                }
            }
            for (int i=0; i<H; i++) {
                for (int j=0; j<W; j++) {
                    if (A[i][j].equals(".")) {
                        if (i > 0 && A[i-1][j].equals("#")) {
                            R[i][j] = "#";
                        }
                        if (i+1 < H && A[i+1][j].equals("#")) {
                            R[i][j] = "#";
                        }
                        if (j > 0 && A[i][j-1].equals("#")) {
                            R[i][j] = "#";
                        }
                        if (j+1 < W && A[i][j+1].equals("#")) {
                            R[i][j] = "#";
                        }
                        if (R[i][j].equals(".")) {
                            fill++;
                        }
                    }
                }
            }
            if (fill == 0) {
                break;
            }
        }

        System.out.println(loop);
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void main(String args[]) throws Exception{
        BufferedReader stdR = new BufferedReader(new InputStreamReader(System.in));
        String[] s = stdR.readLine().split(" ");
        int H = Integer.parseInt(s[0]);
        int W = Integer.parseInt(s[1]);
        char [][] cr = new char[H][W];
        for(int i = 0 ; i < H ; i++) {
            String str = stdR.readLine();
            for(int j = 0 ; j < W ; j++) {
                cr[i][j] = str.charAt(j);
            }
        }
        int count = 0;
        Queue<String> q = new LinkedList<String>();
        for(int i = 0 ; i < H ; i++) {
            for(int j = 0 ; j < W ; j++) {
                if(cr[i][j] == '#') {
                    count++;
                    q.add(j+","+i+","+0);
                }
            }
        }
        while(true) {
            String[] st = q.poll().split(",");
            int nx = Integer.parseInt(st[0]);
            int ny = Integer.parseInt(st[1]);
            int nturn = Integer.parseInt(st[2]);
            if(nx - 1 >= 0 && cr[ny][nx - 1] == '.') {
                cr[ny][nx - 1] = '#';
                q.add((nx - 1)+","+ny+","+(nturn + 1));
                count++;
            }
            if(ny - 1 >= 0 && cr[ny - 1][nx] == '.') {
                cr[ny - 1][nx] = '#';
                q.add(nx+","+(ny - 1)+","+(nturn + 1));
                count++;
            }
            if(nx + 1 < W && cr[ny][nx + 1] == '.') {
                cr[ny][nx + 1] = '#';
                q.add((nx + 1)+","+ny+","+(nturn + 1));
                count++;
            }
            if(ny + 1 < H && cr[ny + 1][nx] == '.') {
                cr[ny + 1][nx] = '#';
                q.add(nx+","+(ny + 1)+","+(nturn + 1));
                count++;
            }
            if(count == H * W)break;
        }
        int max = 0;
        while(!q.isEmpty()) {
            max = Math.max(max, Integer.parseInt(q.poll().split(",")[2]));
        }
        System.out.println(max);
    }
}


import java.util.*;
import java.io.*;

public class Main {
	static BufferedReader br;
	static StringTokenizer tokenizer;
	static int[] xOff = {0, 0, 1, -1};
	static int[] yOff = {1, -1, 0, 0};
	public static void main(String[] args) throws Exception {
		br = new BufferedReader(new InputStreamReader(System.in));
		int n = nextInt();
		int m = nextInt();
		boolean[][] black = new boolean[n][m];
		Queue<Integer> rQ = new ArrayDeque<Integer>();
		Queue<Integer> cQ = new ArrayDeque<Integer>();
		int curr = 0, next = 0, ans = 0;
		for(int i = 0; i < n; i++) {
			String t = next();
			for(int k = 0; k < m; k++) {
				black[i][k] = t.charAt(k) == '#';
				if(black[i][k]) {
					curr++;
					rQ.add(i);
					cQ.add(k);
				}
			}
		}
		while(!rQ.isEmpty()) {
			if(curr == 0) {
				curr = next;
				next = 0;
				ans++;
			}
			curr--;
			int r = rQ.poll();
			int c = cQ.poll();
			for(int i = 0; i < 4; i++) {
				if(r + xOff[i] >= 0 && r + xOff[i] < n && c + yOff[i] >= 0 && c + yOff[i] < m && !black[r + xOff[i]][c + yOff[i]]) {
					next++;
					black[r + xOff[i]][c + yOff[i]] = true;
					rQ.add(r + xOff[i]);
					cQ.add(c + yOff[i]);
				}
			}
		}
		System.out.println(ans);

	}

	public static String next() throws IOException {
		while (tokenizer == null || !tokenizer.hasMoreTokens()) {
			String line = br.readLine();
			if (line == null)
				throw new IOException();
			tokenizer = new StringTokenizer(line);
		}
		return tokenizer.nextToken();
	}

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

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

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


import java.util.*;

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

        Scanner sc = new Scanner(System.in);

        int N = sc.nextInt();
        int[] A = new int[N];
        int[] L = new int[N + 1];
        int[] R = new int[N + 1];
        L[0] = 0;
        R[N] = 0;

        for(int i=0; i<N; i++){
            A[i] = sc.nextInt();
        }
        int max = 0;
        for(int i=0; i<N; i++){
            for(int j=0; j<i; j++){
                if(j==0){
                    L[j + 1] = A[j];
                    continue;
                }
                L[j + 1] = getCommonDivisor(L[j], A[j]);
            }
            for(int j=N-1; j>i; j--){
                if(j==N-1){
                    R[j] = A[j];
                    continue;
                }
                R[j] = getCommonDivisor(R[j + 1], A[j]);
            }
            if(i==0){
                max = Math.max(max, R[i + 1]);
                continue;
            }
            if(i==N-1){
                max = Math.max(max, L[i]);
                continue;
            }
            max = Math.max(max, getCommonDivisor(L[i], R[i + 1]));
        }
        System.out.println(max);
    }

    private static int getCommonDivisor(int x, int y){
        int bigger = Math.max(x, y);
        int smaller = Math.min(x, y);
        int surplus = bigger % smaller;

        if(surplus==0){
            return smaller;
        }
        surplus = getCommonDivisor(smaller, surplus);

        return surplus;
    }
}

Score : 300 points

Problem Statement

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq A_i \leq 10^9

Output

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

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

Sample Input 1

3
7 6 8

Sample Output 1

2

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

Sample Input 2

3
12 15 18

Sample Output 2

6

Sample Input 3

2
1000000000 1000000000

Sample Output 3

1000000000

We can replace an integer with itself.


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 = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();

        // 0からiまでの最大公約数
        int[] leftCache = new int[n];
        leftCache[0] = a[0];
        for (int i = 1; i < n; i++) {
            leftCache[i] = gcd(leftCache[i - 1], a[i]);
//            System.out.println(leftCache[i]);
        }

        // iからn-1までの最大公約数
        int[] rightCache = new int[n];
        rightCache[n - 1] = a[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            rightCache[i] = gcd(rightCache[i + 1], a[i]);
//            System.out.println(rightCache[i]);
        }

        int ans = rightCache[1]; // 左端を除いた場合
        for (int i = 0; i < n - 2; i++) {
            int candidate = gcd(leftCache[i], rightCache[i + 2]);
            if (candidate > ans) {
                ans = candidate;
            }
        }
        // 右端を除いた場合
        if (leftCache[n - 2] > ans) {
            ans = leftCache[n - 2];
        }
        System.out.println(ans);
    }

    static int gcd(int a, int b) {
//        if (a == 0 || b == 0) {
//            return 1;
//        }
        if (a > b) {
            if (a % b == 0) {
                return b;
            } else {
                return gcd(b, a % b);
            }
        } else {
            if (b % a == 0) {
                return a;
            } else {
                return gcd(a, b % a);
            }
        }
    }
}


import java.util.*;

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

        int N = sc.nextInt();

        int[] A = new int[N];
        for (int i = 0; i < N; i++) {
            A[i] = sc.nextInt();
        }

        int res = 0;
        for (int i = 0; i < N; i++) {
            int tmpRes = gcdSkip(A, N, i);
            res = Math.max(tmpRes, res);
        }

        System.out.println(res);
    }

    public static int gcdSkip(int[] A, int N, int skip) {
        int res = 0;
        for (int i = 0; i < N; i++) {
            if (skip == i) continue;
            if (res == 0) {
                res = A[i];
                continue;
            }
            res = gcd(A[i], res);
        }
        return res;
    }

    public static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int[] values = new int[n];
        int[] lefts = new int[n];
        int[] rights = new int[n];

        for (int i = 0; i < n; i++) {
            values[i] = sc.nextInt();
        }

        int result = 0;

        for (int i = 0; i < n; i++) {
            int current = 0;
            for (int j = 0; j < n; j++) {
                if (i==j) {
                    continue;
                }
                current = gcd(current, values[j]);
            }

            result = current > result ? current : result;
        }

        System.out.println(result);
    }

    private static int gcd(int m, int n) {
        if (n == 0) {
            return m;
        }
        int tmp = m % n;
        return gcd(n, tmp);
    }
}


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int N = Integer.parseInt(sc.nextLine());
		String[] list = sc.nextLine().split(" ",0);
		int gcd;
		int a1;
		int tmp;
		int x,y;
		List<Integer> gcdList = new ArrayList<>();
		for (int i=0;i<N;i++) {
			if (i == 0) {
				gcd = Integer.parseInt(list[1]);
			} else {
				gcd = Integer.parseInt(list[0]);
			}
			for (int j=0; j<N; j++) {
				if (j == i) {
					//
				} else {
					a1 = Integer.parseInt(list[j]);
					if (gcd < a1) {
						x = a1;
						y = gcd;
					} else {
						x = gcd;
						y = a1;
					}
					while ((tmp = x % y) != 0) {
						x = y;
						y =tmp;
					}
					gcd = y;
				}
			}
			gcdList.add(gcd);

		}
		int max = Collections.max(gcdList);
		System.out.println(max);
		sc.close();
	}

}


/*
 *ver3
 *l_gcdとr_gcdの配列計算方法変更
 */

import java.util.Scanner;
import java.util.Arrays;

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

	int n = scan.nextInt();
	int[] a = new int[n];
	for(int i = 0; i < n; i++){
	    a[i] = scan.nextInt();
	}

	//最大公約数の配列
	int[] gcd = new int[n];

	//端の処理
	gcd[0] = ruisekiGcd(a, 1, n);
	gcd[n-1] = ruisekiGcd(a, 0, n-1);

	//右側、左側累積GCDを作成
	int[] l_gcd = new int[n];
	int[] r_gcd = new int[n];
	l_gcd[0] = a[0];
	r_gcd[n-1] = a[n-1];
	for(int i = 1; i < n-1; i++){
	    l_gcd[i] = getGcd(l_gcd[i-1], a[i-1]);
	    r_gcd[n-i-1] = getGcd(r_gcd[n-i], a[n-i]);
	}

	//累積GCDを作成
	for(int i = 1; i < n-1; i++){
	    gcd[i] = getGcd(l_gcd[i], r_gcd[i]);
	}

	//累積GCDの最大値を計算
	Arrays.sort(gcd);

	System.out.println(gcd[n-1]);
    }

    static int ruisekiGcd(int[] a, int s, int l){
	int gcd = a[s];
	for(int i = s+1; i < l; i++){
	    gcd = getGcd(gcd, a[i]);
	}
	return gcd;
    }

    static int getGcd(int a, int b){
	if(a < b){
	    int tmp = a;
	    a = b;
	    b = tmp;
	}

	while(b != 0){
	    int tmp = a % b;
	    a = b;
	    b = tmp;
	}

	return a;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class Main {
	int N;
	long[] A;
	long result = 0;

	long gcd(long large, long small) {
		if (large < small) {
			return gcd(small, large);
		}
		if (large == small) {
			return large;
		}
		if (large % small == 0) {
			return small;
		}
		return gcd(small, large % small);
	}

	void calc() {
		List<Long> gcds = new ArrayList<>();
		gcds.add(gcd(A[A.length - 1], A[A.length - 2]));
		int index = A.length - 2;
		for (int i = A.length - 3; i >= 0; --i) {
			long last = gcds.get(gcds.size() - 1);
			long g = gcd(last, A[i]);
			gcds.add(g);
			if (g < last) {
				index = i;
			}
		}

		if (index <= A.length - 3) {
			// その数を置き換える
			long r = A[A.length - 1];
			for (int i = A.length - 2; i >= 0; --i) {
				if (i == index) {
					continue;
				}
				r = gcd(r, A[i]);
			}
			this.result = r;
		} else {
			long r0 = A[A.length - 1];
			for (int i = A.length - 3; i >= 0; --i) {
				r0 = gcd(r0, A[i]);
			}
			long r1 = A[A.length - 2];
			for (int i = A.length - 3; i >= 0; --i) {
				r1 = gcd(r1, A[i]);
			}
			this.result = Math.max(r0, r1);
		}
	}

	Main() throws IOException {
		InputStreamReader reader = new InputStreamReader(System.in, StandardCharsets.UTF_8);
		BufferedReader in = new BufferedReader(reader);
		N = Integer.parseInt(in.readLine());
		A = new long[N];
		String[] tokens = in.readLine().split(" ");
		for (int i = 0; i < N; ++i) {
			A[i] = Integer.parseInt(tokens[i]);
		}
		in.close();
		Arrays.sort(A);
		calc();
	}

	public static void main(String[] args) throws IOException {
		Main ins = new Main();
		System.out.println(ins.result);
	}

}


import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static int n;
	static long r,a,b,ans;
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) {
		n=sc.nextInt();
		long A[]=new long[n];
		for(int i=0;i<n;i++)A[i]=sc.nextLong();
		Arrays.sort(A);
		ans=0;
		b=A[0];
		for(int i=1;i<n;i++) {
			long temp=gcd(A[i],b);
			if(ans<temp)ans=temp;
		}
		System.out.println(ans);
		}
	public static long gcd(long a,long b) {
		while ((r = a % b) != 0) {
			a = b;
			b = r;
			}
		return b;
	}
}


import java.util.*;

public class Main{

    public static void main(String args[]){

        // スキャナーの宣言
        Scanner sc = new Scanner(System.in);
        // 整数の入力
		int n = sc.nextInt();
        int[] a = new int[n];
        //int min = Integer.MAX_VALUE;
        int num;//最大公約数
        a[0] = sc.nextInt();
        a[1] = sc.nextInt();
        int tmp;
        int x;
        int y;
        /*while ((tmp = x % y) != 0) {
            x = y;
            y = tmp;
        }
        num = y;*/
        //System.out.println(num);
        for(int i = 2; i < n; i++){
            a[i] = sc.nextInt();
            /*x = Math.max(num, a[i]);
            y = Math.min(num, a[i]);
            //min = Math.min(a[i], min);
            while ((tmp = x % y) != 0) {
                x = y;
                y = tmp;
            }
            num = y;*/
        }
        //System.out.println(num);
        int ans = 0;
        boolean b = true;
        /*for(int i = 1; i < min + 1; i++){
            for(int j = 0;j < n; j++){
                if(a[j] % i != 0) b = false;
            }
            if(b) ans = Math.max(i, ans);
            b = true;
        }*/
        /*for(int i = 0; i < n; i++){
            for(int j = 1; j < num + 1; j++){
                for(int k = 0; k < n; k++){
                    if(k != i && a[k] % j != 0){
                        b = false;
                        break;
                    }
                }
                if(b) ans = Math.max(j, ans);
                b = true;
            }
        }*/
        int l = 0;
        for(int i = 0; i < n; i++){
            if(n == 2){
                ans = Math.max(a[0], a[1]);
                break;
            }
            if(i != 0 && i != 1){
                x = Math.max(a[0], a[1]);
                y = Math.min(a[0], a[1]);
                while ((tmp = x % y) != 0) {
                    x = y;
                    y = tmp;
                }
                l = y;
            }else if(i == 0){
                x = Math.max(a[2], a[1]);
                y = Math.min(a[2], a[1]);
                while ((tmp = x % y) != 0) {
                    x = y;
                    y = tmp;
                }
                l = y;
            }else if(i == 1){
                x = Math.max(a[0], a[2]);
                y = Math.min(a[0], a[2]);
                while ((tmp = x % y) != 0) {
                    x = y;
                    y = tmp;
                }
                l = y;
            }
            for(int j = 2; j < n; j++){
                if(i != j){
                    x = Math.max(l, a[j]);
                    y = Math.min(l, a[j]);
                    while ((tmp = x % y) != 0) {
                        x = y;
                        y = tmp;
                    }
                    l = y;
                }
            }
            ans = Math.max(l, ans);
        }

        // 出力
        System.out.println(ans);

    }

}


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 = new int[N];
		for(int i = 0; i < N ; i++) {
			A[i] = sc.nextInt();
		}

		A[0] = A[1];

		sc.close();

		int answer = gcd(A[0],A[1]);

		for(int i = 1 ; i < N - 1 ;i ++) {
			answer = gcd(answer, A[i+1]);
		}

		System.out.println(answer);
	}

	public static int gcd(int a, int b) {
		int tmp;
		if(b > a) {
			tmp = a;
			a = b;
			b = tmp;
		}

	    int r = -1;
	    while (r != 0) {
	        r = a % b;
	        a = b;
	        b = r;
	    }

	    return a;
	}

}


import java.util.Scanner;

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

    while (in.hasNext()) {
      int N = in.nextInt();
      int[] A = new int[N];

      for (int i = 0; i < A.length; ++i) {
        A[i] = in.nextInt();
      }

      int[] gcdBefore = new int[N];
      gcdBefore[0] = 0;
//      gcdBefore[1] = A[0];
      for (int i = 1; i < gcdBefore.length; ++i) {
        gcdBefore[i] = gcd(gcdBefore[i - 1], A[i - 1]);
      }

      int[] gcdAfter = new int[N];
      gcdAfter[gcdAfter.length - 1] = 0;
 //     gcdAfter[gcdAfter.length - 2] = A[A.length - 1];
      for (int i = gcdAfter.length - 2; i >= 0; --i) {
        gcdAfter[i] = gcd(gcdAfter[i + 1], A[i + 1]);
      }

      int ans = -1;
      for (int i = 0; i < A.length; ++i) {
        ans = Math.max(ans, gcd(gcdBefore[i], gcdAfter[i]));
      }

      System.out.println(ans);
    }
  }

  private static int gcd (int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}


import java.util.*;
class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = Integer.parseInt(sc.next());
        int[] a = new int[N];
        for(int i = 0; i<N; i++) {
            a[i] = Integer.parseInt(sc.next());
        }
        if(N==2) {
            System.out.println(Math.max(a[0],a[1]));
            return;
        }
        int ans = 0;
        int gcda = a[0];
        int min = Integer.MAX_VALUE;
        int minI = 0;
        int preMinI = 0;
        for(int i = 0; i<N; i++) {
            gcda = gcd(gcda,a[i]);
            if(min > gcda) {
                min = gcda;
                preMinI = minI;
                minI = i;
            }
        }
        //        System.out.println(minI);
        gcda = a[0];
        for(int i = 0; i<N; i++) {
            if(minI == 0 && i == minI) {
                gcda = a[1];
                continue;
            }
            if(i == minI)continue;
            gcda = gcd(gcda, a[i]);
        }
        ans = gcda;

        for(int i = 0; i<N; i++) {
            if(preMinI == 0 && i == preMinI) {
                gcda = a[1];
                continue;
            }
            if(i == preMinI)continue;
            gcda = gcd(gcda, a[i]);
        }

        System.out.println(Math.max(ans, gcda));
    }

    public static int gcd(int a, int b) {
        if(b==0)return a;
        return gcd(b, a%b);
    }
}


import java.util.*;

public class Main {

    static final long MOD  = 998_244_353;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        int sum = 0;
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
            sum += a[i];
        }
        long[][] dp = new long[n+1][sum+1];
        long[][] dp2 = new long[n+1][sum+1];
        dp[0][0] = 1;
        dp2[0][0] = 1;
        int tmpSum = 0;
        for (int i = 1; i < n+1; i++) {
            tmpSum += a[i-1];
            for(int j = 0; j < tmpSum+1; j++){
                if(a[i-1] <= j) dp[i][j] += dp[i-1][j-a[i-1]];
                dp[i][j] %= MOD;
                dp[i][j] += dp[i-1][j]*2;
                dp[i][j] %= MOD;

                if(a[i-1] <= j) dp2[i][j] += dp2[i-1][j-a[i-1]];
                dp2[i][j] %= MOD;
                dp2[i][j] += dp2[i-1][j];
                dp2[i][j] %= MOD;
            }
        }
        long ans = modPow(3, n);
        for (int i = (sum+1)/2; i < sum+1; i++) {
            ans -= dp[n][i] * 3;
            if(ans < 0)ans += MOD;
        }
        if(sum % 2 == 0){
            ans += dp2[n][sum/2] * 3;
            ans %= MOD;
        }
        System.out.println(ans);
        sc.close();
    }

    public static long modPow(long base, int exp) {
        long ret = 1;
        while(exp > 0){
            if((exp & 1) == 1){
                ret = ret * base %MOD;
            }
            base = base * base %MOD;
            exp >>= 1;
        }
        return ret;
    }

}

Score : 600 points

Problem Statement

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

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

Constraints

3 \leq N \leq 300

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

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
a_1
:
a_N

Output

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

Sample Input 1

4
1
1
1
2

Sample Output 1

18

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

Sample Input 2

6
1
3
2
3
5
2

Sample Output 2

150

Sample Input 3

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

Sample Output 3

563038556


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int A = sc.nextInt();
		int B = sc.nextInt();
		int C = sc.nextInt();
		if (B>=A*C) {
			System.out.println(C);
			return ;
		}
		System.out.println(B/A);
	}
}

Score : 100 points

Problem Statement

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

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

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

How many times will he hear the sound?

Constraints

All values in input are integers.

1 \leq A, B, C \leq 100

Input

Input is given from Standard Input in the following format:

A B C

Output

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

Sample Input 1

2 11 4

Sample Output 1

4

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

Sample Input 2

3 9 5

Sample Output 2

3

He may not be able to be satisfied.

Sample Input 3

100 1 10

Sample Output 3

0


import java.util.*;
public class Main {
  public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    int A = sc.nextInt();
    int B = sc.nextInt();
    int C = sc.nextInt();

    if ((B / A) < C) {
      System.out.println(B / A);
    } else {
      System.out.println(C);
    }

  }
}


import java.io.*;
        import java.util.Scanner;

public class Main{
    public static void main(String []args) throws IOException
    {
        Scanner sc = new Scanner(System.in);
        int  a = sc.nextInt();
        int  b = sc.nextInt();
        int  c = sc.nextInt();
        int x = a/b;
        if(x>c)
            System.out.println(c);
        else
            System.out.println(x);

    }
}


import java.util.*;

public class Main {

  public static void main (String[] args){

    Main main = new Main();
    main.solve();
  }

  private void solve (){

    Scanner scanner = new Scanner (System.in);

    int A = scanner.nextInt();
    int B = scanner.nextInt();
    int C = scanner.nextInt();

    int kaisuu = B/A;

    if (kaisuu>=C){
      System.out.println(C);
    } else {
      System.out.println(kaisuu);
    }
  }
}


import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String args[]) {
		Scanner scn = new Scanner(System.in);
		int a = scn.nextInt();
		int b = scn.nextInt();
		int k = scn.nextInt();

		ArrayList<Integer> list = new ArrayList<>();

		int i = 1;
		do {
			if (a % i == 0 && b % i == 0) {
				System.out.println(i);
				list.add(i);
			}
			i++;
		} while (i <= a);

		System.out.println(list.get((list.size()-k)));
	}
}


//import java.util.List;
import java.util.Scanner;
//import java.util.Stack;

public class Main {

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

		int times = 0;
		int max = Math.max(A, B);
		int output = max;
		for(int i = max; i >= 1; i--) {
			if(A%i == 0 && B%i == 0) {
				times++;
				output = i;
				if(times == K) {
					break;
				}
			}
		}
		System.out.println(output);

	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int a = sc.nextInt();
		int b = sc.nextInt();
		int c = sc.nextInt();

		if(a>b) {
			System.out.println(0);
		}else {
			if(a*c<b) {
				System.out.println(c);
			}else if(a*c == b){
				System.out.println(c);
			}else {
				System.out.println(a);
			}
		}

	}
}


import java.util.Scanner;

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

		int a=Math.min(B/A, C);

		System.out.println(a);
	}
}


import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();
        System.out.println(Math.min(b / a, c));
    }

}


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

public class Main
{
  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) {}
      }
      return st.nextToken();
    }

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

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

  }

  public static void main(String[] args) {
    FastScanner fs = new FastScanner();
    int n = fs.nextInt();
    int[] arr = new int[n];
    for(int i = 0; i < n; ++i) {
      arr[i] = fs.nextInt();
    }
    int[] dp = new int[n];
    dp[1] = (int)Math.abs(arr[1]-arr[0]);
    for(int i = 2; i < n; ++i) {
      dp[i] = Math.min(dp[i-1] + (int)Math.abs(arr[i-1]-arr[i]),
          dp[i-2] + (int)Math.abs(arr[i-2]-arr[i]));
    }
    PrintWriter out = new PrintWriter(System.out);
    out.println(dp[n-1]);
    out.close();
  }

}

Score : 100 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

4
10 30 40 20

Sample Output 1

30

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

Sample Input 2

2
10 10

Sample Output 2

0

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

Sample Input 3

6
30 10 60 10 60 50

Sample Output 3

40

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


import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner scn = new Scanner(System.in);
		int n = scn.nextInt();
		int[] arr = new int[n];
		for(int i=0;i<n;i++){
		    arr[i] = scn.nextInt();
		}
		int ans = solution(0,arr);
        System.out.println(ans);
	}

	public static int solution(int idx,int[] arr){
	    if(idx==arr.length-1)return 0;
	    int ans = 0;
	    int o1 = idx+1<arr.length?solution(idx+1,arr)+Math.abs(arr[idx+1]-arr[idx]):1000000;
	    int o2 = idx+2<arr.length?solution(idx+2,arr)+Math.abs(arr[idx+2]-arr[idx]):1000000;
	    return Math.min(o1,o2);
	}
}


import java.util.*;
public class Main
{
  public static void main(String[] args )
  {
    Scanner scn = new Scanner(System.in) ;

    int n = scn.nextInt() ;

    int[] arr =new int[n] ;

    for(int i =0 ; i < n; i++ ) arr[i] = scn.nextInt() ;

    if( n== 1 )
    {
     System.out.print(0) ;
    }
    else{
    long[] dp = new long[n];

      dp[0] =  0 ;
      dp[1] =  (long)Math.abs(arr[1] - arr[0] ) ;

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

         long opt1  =  dp[i-1] + (long)Math.abs(arr[i] - arr[i-1] ) ;

         long opt2  =  dp[i-2] + (long)Math.abs(arr[i] - arr[i-2] ) ;

        dp[i] =  Math.min(opt1 , opt2 ) ;

     }

      System.out.print(dp[n-1]) ;

    }

  }

}


import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] h = new int[n];
        for (int i = 0; i < n; i++) {
            h[i] = sc.nextInt();
        }
        int[] cost = new int[n];
        cost[0] = 0;
        cost[1]= Math.abs(h[1]-h[0]);

        for(int i = 2;i<n;i++){
            int tmp1 = Math.abs(h[i-1]-h[i])+ cost[i-1];
            int tmp2 = cost[i-2]+ Math.abs(h[i-2]-h[i]);
            cost[i] = Math.min(tmp1,tmp2);
        }
        System.out.println(cost[n-1]);

    }

}


import java.util.*;
public class Main {
    public static long mini(int a[],int n)
    {
       int dp[]=new int[n];
       dp[0]=0;
       dp[1]=Math.abs(a[1]-a[0]);
       for(int i=2;i<n;i++)
       {
           dp[i]=Math.min(Math.abs(a[i]-a[i-2])+dp[i-2],Math.abs(a[i]-a[i-1])+dp[i-1]);
       }
       return dp[n-1];
    }
    public static void main(String args[]) {
        Scanner s=new Scanner(System.in);
        int n=s.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++)
        {
            a[i]=s.nextInt();
        }
        System.out.println(mini(a,n));
    }
}


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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] nw = br.readLine().split(" ");

        int N = Integer.parseInt(nw[0]);
        int W = Integer.parseInt(nw[1]);

        int[][] weight = new int[N][2];

        for(int i=0; i<N; i++) {
            String[] input = br.readLine().split(" ");
            weight[i][0] = Integer.parseInt(input[0]);
            weight[i][1] = Integer.parseInt(input[1]);
        }

        System.out.println(getMaxValue(weight, W));
    }

    private static int getMaxValue(int[][] weight, int W) {
        int[][] dp = new int[weight.length + 1][W+1];

        for(int i=1; i<=weight.length; i++) {
            for(int j=1; j<=W; j++) {
                dp[i][j] = dp[i-1][j];

                if(weight[j-1][0] <= j) {
                    dp[i][j] = Math.max(dp[i][j], weight[j-1][1] + dp[i-1][W-weight[j-1][0]]);
                }
            }
        }

        return dp[weight.length][W];
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

/**
 * Built using CHelper plug-in Actual solution is at the top
 */
public class Main {
	public static void main(String[] args) {
		InputReader in = new InputReader(System.in);
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), true);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.flush();
		out.close();
	}
}

class Pair {
	long first;
	long second;
	long third;

	Pair(long first, long second, long third) {
		this.first = first;
		this.second = second;
		this.third = third;
	}
}

class TaskB {

	public void solve(int testNumber, InputReader in, PrintWriter pw) {
		int N = in.nextInt();
		int h[] = new int[N];
		for (int i = 0; i < N; i++) {
			h[i] = in.nextInt();
		}
		int dp[] = new int[N];
		Arrays.fill(dp, Integer.MAX_VALUE);
		dp[0] = 0;
		for (int i = 0; i < N; i++) {
			for (int j : new int[] { i + 1, i + 2 }) {
				if (j < N) {
					dp[j] = Math.min(dp[j], dp[i] + Math.abs(h[i] - h[j]));
				}
			}
		}
		pw.println(dp[N - 1]);

	}

	int __gcd(int a, int b) {
		if (b == 0)
			return a;
		return __gcd(b, a % b);

	}

	public int getInt(int num) {
		int ret = -1;
		switch (num) {
		case 0:
			ret = 6;
			break;
		case 1:
			ret = 2;
			break;
		case 2:
			ret = 5;
			break;
		case 3:
			ret = 5;
			break;
		case 4:
			ret = 4;
			break;
		case 5:
			ret = 5;
			break;
		case 6:
			ret = 6;
			break;
		case 7:
			ret = 3;
			break;
		case 8:
			ret = 7;
			break;
		case 9:
			ret = 6;
			break;
		}
		return ret;
	}

	public int isPow(long num) {
		int count = 0;
		while (num > 0) {
			num /= 2;
			count++;
		}
		return count;
	}
}

class InputReader {
	BufferedReader br;
	StringTokenizer st;

	public InputReader(InputStream in) {
		br = new BufferedReader(new InputStreamReader(in));
		st = null;
	}

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

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

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

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


import java.util.*;
public class Main{
    public static void main(String[] args) {
        Scanner ob=new Scanner(System.in);
        int n=ob.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++){
            a[i]=ob.nextInt();
        }
        int arr[]=new int[n];
        arr[0]=0;
        arr[1]=Math.abs(a[1]-a[0]);
        for(int i=2;i<n;i++){
            arr[i]=Math.min(arr[i-2]+Math.abs(a[i]-a[i-2]),arr[i-1]+Math.abs(a[i]-a[i-1]));
        }
        System.out.println(arr[n-1]);
        ob.close();
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;

// import
class Main {

    static int min(int a,int b)
    {
        return Math.min(a, b);
    }

    static int abs(int a)
    {
        return Math.abs(a);
    }

    public static void main(String[] args) throws Exception {
        PrintWriter p = new PrintWriter(System.out);
        // Scanner sc = new Scanner(System.in);
        // int n = sc.nextInt();
        // sc.nextLine();
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(bf.readLine());
        Integer arr[] = Arrays.stream(bf.readLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);

        int dp[] = new int[n+1];
        // int mod = 100000000+7;
        Arrays.fill(dp, Integer.MAX_VALUE); //fill large values in dp
        dp[0] = 0;
        for (int i = 0; i < n; i++)
        {
            if(i+1 < n )
                dp[i+1] =  min(dp[i+1],dp[i]+abs(arr[i]-arr[i+1]));
            if (i + 2 < n)
                dp[i + 2] = min(dp[i + 2], dp[i] + abs(arr[i] - arr[i+2]));

        }
        // System.out.println(Arrays.toString(dp));
        // System.out.println(dp[n-1]);
        p.println(dp[n-1]);
        p.flush();
    }
}


import java.util.Scanner;

class Main {
	int n;
	int[] h;
	int[] cost;

	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		Main m = new Main(sc);
		m.solve();
	}
	Main(Scanner sc){
		n = sc.nextInt();
		h = new int[n];
		cost = new int[n];
		for(int i = 0; i < n;i++){
			h[i] = sc.nextInt();
			cost[i] = Integer.MAX_VALUE;
		}
		cost[0] = 0;
	}
	int cntString(String str,char target){
		int cnt = 0;
		for(char s : str.toCharArray()){
			if(s == target){
				cnt++;
			}
		}
		return cnt;
	}
	boolean[] checked;
	void solve(){
		checked = new boolean[n];
		for(int i=1;i<n;i++) checked[i] = false;
		checked[0] = true;
		System.out.println(reSolve(n-1));
	}
	int reSolve(int num){
		if(checked[num]) return cost[num];
		cost[num] = Math.min(cost[num], reSolve(num-1)+Math.abs(h[num]-h[num-1]));
		if (num>1) cost[num] = Math.min(cost[num], reSolve(num-2)+Math.abs(h[num]-h[num-2]));
		checked[num] = true;
		return cost[num];
	}
}


import java.util.Scanner;
import java.lang.Math;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        int[] stones = new int[N];
        for(int i = 0; i < N; i++) stones[i] = scanner.nextInt();

        int[] dp = new int[N];
        dp[1] = Math.abs(stones[1] - stones[0]);
        for(int i = 2; i < N; i++) {
            dp[i] = Math.min(Math.abs(stones[i] - stones[i - 2]) + dp[i - 2],
                    Math.abs(stones[i] - stones[i - 1]) + dp[i - 1]);
        }
        System.out.println(dp[N - 1]);
    }
}


/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;
import java.lang.*;

class Main {
    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;
        }
    }

    static boolean is_palindrome(String s){
        for (int i=0;i<=s.length()/2 ;i++ ) {
            if(s.charAt(i)!=s.charAt(s.length()-1-i)){
                return false;
            }
        }
        return true;
    }
	public static void main (String[] args) {
	    FastReader ob = new FastReader();
	    int n = ob.nextInt();
	    int arr[] = new int[n];
	    for (int i=0;i<arr.length ;i++ ) {
	        arr[i]=ob.nextInt();
	    }
	    long dp[] = new long[n];
	    dp[0]=0;
	    dp[1]=Math.abs(arr[1]-arr[0]);
	    dp[2]=Math.min(dp[1]+Math.abs(arr[1]-arr[2]),Math.abs(arr[2]-arr[0]));
	    for(int i=3;i<n;i++){
	        dp[i]=Math.min(dp[i-1]+Math.abs(arr[i]-arr[i-1]),dp[i-2]+Math.abs(arr[i-2]-arr[i]));
	    }
	    System.out.println(dp[n-1]);
	}
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int N = input.nextInt();
		int[] test = new int[N];
		for (int i = 0; i < N; i++) {
			test[i] = input.nextInt();
		}
		System.out.println(JUMP(test));
	}
	public static int JUMP(int[] test) {
		int[] dp = new int[test.length];
		dp[0]=0;
		dp[1]=Math.abs(test[1]-test[0]);
		for (int i = 2; i < test.length; i++) {
			dp[i]=Math.min(dp[i-1]+Math.abs(test[i]-test[i-1]), dp[i-2]+Math.abs(test[i]-test[i-2]));
		}
		return dp[test.length-1];
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        Reader in = new Reader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        AFrog1 solver = new AFrog1();
        solver.solve(1, in, out);
        out.close();
    }

    static class AFrog1 {
        public void solve(int testNumber, Reader in, PrintWriter out) {
            int n = in.nextInt();
            int[] a = new int[n];
            for (int i = 0; i < n; ++i) {
                a[i] = in.nextInt();
            }
            int c = 0;
            int d = Math.abs(a[1] - a[0]);
            for (int i = 2; i < n; ++i) {
                int x = Math.abs(a[i] - a[i - 1]) + d;
                int y = Math.abs(a[i] - a[i - 2]) + c;
                int z = Math.min(x, y);
                c = d;
                d = z;
            }
            out.println(d);
        }

    }

    static class Reader {
        final private int BUFFER_SIZE = 1 << 16;
        private DataInputStream din;
        private byte[] buffer;
        private int bufferPointer;
        private int bytesRead;

        public Reader(InputStream in) {
            din = new DataInputStream(in);
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public Reader(String file_name) {
            try {
                din = new DataInputStream(new FileInputStream(file_name));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            buffer = new byte[BUFFER_SIZE];
            bufferPointer = bytesRead = 0;
        }

        public int nextInt() {
            int ret = 0;
            byte c = read();
            while (c <= ' ') {
                c = read();
            }
            boolean neg = (c == '-');
            if (neg) {
                c = read();
            }
            do {
                ret = ret * 10 + c - '0';
            } while ((c = read()) >= '0' && c <= '9');

            if (neg) {
                return -ret;
            }
            return ret;
        }

        private void fillBuffer() {
            try {
                bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
                if (bytesRead == -1) {
                    buffer[0] = -1;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        private byte read() {
            if (bufferPointer == bytesRead) {
                fillBuffer();
            }
            return buffer[bufferPointer++];
        }

    }
}


import java.util.*;
import java.lang.Math;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		int number_of_elements = sc.nextInt();
      	int intArray[] = new int[number_of_elements];
      	int index = 0;
      	while(sc.hasNextInt()){
          intArray[index++] = sc.nextInt();
        }
      int dpArray[] = new int[intArray.length];
      int cost = 0;
      dpArray[0]=0;
      dpArray[1]=Math.abs(intArray[1]-intArray[0]);
      for(int i =2 ;i<dpArray.length;i++){
      	dpArray[i]=Math.min(dpArray[i-2]+Math.abs(intArray[i]-intArray[i-2]),dpArray[i-1]+Math.abs(intArray[i]-intArray[i-1]));
      }
      System.out.println(dpArray[dpArray.length-1]);
	}
}


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

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = getInt(br.readLine()); // 1行目取得
        int[] h = getIntArray(br.readLine()); // ２行目取得

        int[] dp = new int[N];
        dp[0] = 0;

        for(int i = 1; i < N; i++) {
            execute(i, h, dp);
        }
        System.out.println(dp[N-1]);
    }

    public static void execute(int i, int[] h, int[] dp) {
        if(i == 1) {
            dp[i] = Math.abs(h[i] - h[i-1]);
        } else {
            // i-1 or i-2 の小さい方を dp[i] に入れる
            int a = Math.abs(h[i] - h[i-1]);
            int b = Math.abs(h[i] - h[i-2]);
            if(a < b) {
                dp[i] = a + dp[i-1];
            } else {
                dp[i] = b + dp[i-2];
            }
        }
    }

    // 標準入力を文字列で取得
    public static String getString(String line) {
        return line;
    }
    // 標準入力を文字列の配列で取得
    public static String[] getStringArray(String line) {
        return line.split(" ");
    }
    // 標準入力を数値で取得
    public static int getInt(String line) {
        return Integer.parseInt(line);
    }
    // 標準入力を数値の配列で取得
    public static int[] getIntArray(String line) {
        String[] strArr = line.split(" ");
        int[] intArr = new int[strArr.length];
        for(int i = 0; i < strArr.length; i++) {
            intArr[i] = Integer.parseInt(strArr[i]);
        }
        return intArr;
    }

    // 文字列配列を数値配列に変換
    public static int[] strToInt(String[] s) {
        int[] arr = new int[s.length];
        for(int i = 0; i < s.length; i++) {
            arr[i] = Integer.parseInt(s[i]);
        }
        return arr;
    }
    // 文字列を数値に変換
    public static int strToInt(String s) {
        return Integer.parseInt(s);
    }
}


import java.util.Scanner;

public class Main {

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

		for (int i = 0; i < N; i++) {
			heights[i] = sc.nextInt();
		}
		System.out.println(frog(heights));
	}

	private static int frog(int[] heights) {
		int len = heights.length;
		int[] dp = new int[len];
		dp[0] = 0;
		dp[1] = Math.abs(heights[0] - heights[1]);

		for (int i = 2; i < len; i++) {
			dp[i] = Math.abs(Math.min(dp[i-1] + Math.abs(heights[i-1]-heights[i]),
					                  dp[i-2] + Math.abs(heights[i-2]-heights[i])));
		}

		return dp[len-1];
	}

}


//Pradeep Ghosh 2017076;Lab5-Q-3;

import java.util.*;

import java.lang.*;

import java.io.*;

import java.math.*;

public class Main
{
    public static long[] array = new long[1000001];

    // public static HashMap<long, long> map = new HashMap<>();

    public static int swap1(int[][] student, int[][] professor, int[] student_list, int[] professor_list,int curr_prof,int stud, int prof, int n, int flag){

                        int j3=1;

                        // int flag=0;

                        while(j3<n+1){

                            if(student[stud][j3]==prof){

                                flag=1;

                                break;

                            }

                            else if(student[stud][j3]==curr_prof){

                                break;

                            }

                            j3++;

                        }
                        return flag;

    }

    public static void swap3(int[] student_list, int[] professor_list, int stud, int prof, int curr_prof){

        student_list[stud]=prof; professor_list[curr_prof]=0; professor_list[prof]=1;

    }

    public static void filling1(long[] array1,long left,long right,long[] array,long[] aux){
        array1[0]=left;
        while(array1[0]<right+1){
            array[(int)array1[0]]=aux[(int)array1[0]];
            array1[0]=array1[0]+1;
        }
    }

    public static void swap5(int[] student_list, int[] professor_list, int[][] student, int[][] professor, int n, int total){

        int num=0;

        while(num!=total){

                int prof = 0;

                int j1=1;

                prof=swap2(j1,professor_list,prof,n);

                int j2=1;

                ArrayList<Integer> list = new ArrayList<Integer>();

                while(j2<n+1){

                    int stud = professor[prof][j2];

                    if(student_list[stud]!=0){

                        int curr_prof = student_list[stud];

                        int flag=0;

                        flag=swap1(student,professor,student_list,professor_list,curr_prof,stud,prof,n,flag);

                        if(flag!=0){

                            swap3(student_list,professor_list,stud,prof,curr_prof);

                            break;

                        }

                    }

                    else{

                        total = swap4(professor_list,student_list,prof,stud,total);

                        break;

                    }

                    j2++;

                }

            }

    }

    public static int max_sum(int[][] array,int i, int j,int n,boolean[][] array2){

        int sum=array[i][j];
        if(i>n || j>n){
            // int sum = 0;
            return 0;
        }else if(array2[i][j]==true){
            // System.out.println(i+" "+j);
            return sum;
        }else{
            array[i][j]=Math.max(max_sum(array,i+1,j,n,array2),max_sum(array,i,j+1,n,array2));
            array2[i][j]=true;
            return array[i][j];
        }

    }

    public static void filling3(long[] array1,long[] array,long[] aux,long right){
        while(array1[1]<right+1){
            aux[(int)array1[2]]=array[(int)array1[1]];
            array1[2]=array1[2]+1;
            array1[1]=array1[1]+1;
        }
    }

    public static void mergesort(long[] array, long left, long right, long size,long[] aux){
        long count=0;
        if(left<right){
            long mid = (left+right)/2;
            mergesort(array,mid+1,right,size,aux);
            mergesort(array,left,mid,size,aux);
            merge(array,left,mid+1,right,size,aux);
            // count=count1+count2+count3;
        }
        // return count;
    }

    public static void update(int[] a1, int[] a2 , int n){

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

            a1[a2[i]]=i;

        }
    }

    public static long checking(long j){
        if(j==1){
            return 0;
        }
        else{
            if(j%2!=0){
                return 1+checking(3*j+1);
            }else{
                return 1+checking(j/2);
            }
        }
    }

    public static long horse_path(long n, long m, long start1, long start2){
        if(n==start1 && start2==m){
            return 0;
        }else if(start1>n || start2>m){
            return -1;
        }else{
            long a,b;
            if(horse_path(n,m,start1+2,start2+1)==-1){
                a = 0+horse_path(n,m,start1+2,start2+1);
            }else{
                a=1+horse_path(n,m,start1+2,start2+1);
            }
            if(horse_path(n,m,start1+1,start2+2)==-1){
                b = 0+horse_path(n,m,start1+1,start2+2);
            }else{
                b=1+horse_path(n,m,start1+1,start2+2);
            }
            return min_val(a,b);
        }
    }

    public static long looping(long[] array, int n, int i, long maximum, long value1, long value2){
        while(i<n){
            long temp=value2+array[i];
            maximum =  max(temp,value1);
            value2=store(array,n,value1);
            value1=store(array,n,maximum);
            i++;
        }
        return maximum;
    }

    public static void Result(long value){

        System.out.println(value);

    }

    public static long store(long[] array,int n,long a){
        return a;
    }

    public static long storing(long n){
        long count = 0;
        while(n!=1){
            if(n%2==0){
                count++;
                n=n/2;
            }else{
                count++;
                n=3*n+1;
            }
        }
        return count;
    }

    public static long min_val(long a, long b){
        if(a>b){
            return a;
        }else{
            return b;
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] array =new int[n];
        for(int i=0;i<n;i++){
            array[i]=sc.nextInt();
        }
        int result = height(array,n,0);
        System.out.println(result);
    }

    public static int height(int[] array,int n,int indx){
        if(indx>=n-1){
            return 0;
        }else if(indx==n-2){
            return Math.abs(array[indx]-array[indx+1]);
        }
        else{
            return Math.min(Math.abs(array[indx]-array[indx+1])+height(array,n,indx+1),Math.abs(array[indx]-array[indx+2])+height(array,n,indx+2));
        }
    }

    public static boolean comparing(String s,int odd, int k){
        if(odd<=k && s.length()>=k){
            return true;
        }else{
            return false;
        }
    }

    public static int oddcount(int[] array, String s, int n){
        for(int i=0;i<s.length();i++){
            if(s.substring(i,i+1).equals("a")){
                array[1]++;
            }else if(s.substring(i,i+1).equals("b")){
               array[2]++;
            }else if(s.substring(i,i+1).equals("c")){
               array[3]++;
            }else if(s.substring(i,i+1).equals("d")){
               array[4]++;
            }else if(s.substring(i,i+1).equals("e")){
               array[5]++;
            }else if(s.substring(i,i+1).equals("f")){
               array[6]++;
            }else if(s.substring(i,i+1).equals("g")){
               array[7]++;
            }else if(s.substring(i,i+1).equals("h")){
               array[8]++;
            }else if(s.substring(i,i+1).equals("i")){
               array[9]++;
            }else if(s.substring(i,i+1).equals("j")){
                array[10]++;
            }else if(s.substring(i,i+1).equals("k")){
                array[11]++;
            }else if(s.substring(i,i+1).equals("l")){
                array[12]++;
            }else if(s.substring(i,i+1).equals("m")){
                array[13]++;
            }else if(s.substring(i,i+1).equals("n")){
                array[14]++;
            }else if(s.substring(i,i+1).equals("o")){
                array[15]++;
            }else if(s.substring(i,i+1).equals("p")){
                array[16]++;
            }else if(s.substring(i,i+1).equals("q")){
                array[17]++;
            }else if(s.substring(i,i+1).equals("r")){
                array[18]++;
            }else if(s.substring(i,i+1).equals("s")){
                array[19]++;
            }else if(s.substring(i,i+1).equals("t")){
                array[20]++;
            }else if(s.substring(i,i+1).equals("u")){
                array[21]++;
            }else if(s.substring(i,i+1).equals("v")){
                array[22]++;
            }else if(s.substring(i,i+1).equals("w")){
                array[23]++;
            }else if(s.substring(i,i+1).equals("x")){
                array[24]++;
            }else if(s.substring(i,i+1).equals("y")){
                array[25]++;
            }else if(s.substring(i,i+1).equals("z")){
                array[26]++;
            }
        }
        return oddchecking(array, n);
    }

    public static int oddchecking(int[] array, int n){
        int odd=0;
        for(int j=1;j<n+1;j++){
            if(array[j]%2!=0){
                odd++;
            }
        }
        return odd;
    }

    public static int printDivisors(int n)
    { int c=0;
        // Note that this loop runs till square root
        for (int i=1; i<=Math.sqrt(n); i++)
        {
            if (n%i==0)
            {
                if(n/i==i){
                    c++;
                }else{
                    c=c+2;
                }
            }
        }
        return c;
    }

    public static long gcd(long a, long b)
    {
      if (b == 0){
        return a;
      }
      else{
        return gcd(b,a%b);
      }
    }

    public static long money(long[] array,long n,long sum,long i1,long i2){

        for(int k=(int)n-1;k>=0;k--){
            i1++;
            array[k]=array[k]%1000000007;
            sum=(sum+(array[k]*((i1*i2)%1000000007)))%1000000007;
            i2=(i1*i2)%1000000007;
        }

        return sum;
    }

    public static int largestsum(int[][] array,int i,int j,int n){
        if(i>n || j>n){
            return 0;
        }
        else{
            return array[i][j]+Math.max(largestsum(array,i+1,j,n),largestsum(array,i+1,j+1,n));
        }
    }

    public static void LongestIncreasingSubsequence(long[] array, long n){
        boolean flag=true;
        for(int i=2;i<=n;i++){
            if(array[i]>=array[i-1])
            {
                flag=false;
                break;
            }
        }
        if(flag)
            System.out.println(0);
        else{
        long count=0;
        long maximum=0;
        for(int i1=1;i1<=n;i1++){
            long m1=0;
            long l1=0;
            for(int i2=1;i2<i1;i2++){
                if(array[i2]<=array[i2+1] && array[i2+1]<=array[i1]){
                    l1++;
                }else{
                    if(l1!=0){
                        l1++;
                    }
                    if(m1<l1){
                        m1=l1;
                        l1=0;
                    }else{
                        l1=0;
                    }
                }
            }
            if(m1<l1){
                m1=l1;
            }

            long m2=0;
            long l2=0;
            for(int i2=i1;i2<=n;i2++){
                if(i2==n && array[i2]>=array[i1]){
                    l2++;
                    if(m2<=l2){
                        m2=l2;
                        l2=0;
                    }
                }
                else if(i2==n && array[i2]<array[i1]){
                    if(m2<l2){
                        m2=l2;
                        l2=0;
                    }
                }
                else if(i2!=n && array[i2]<=array[i2+1] && array[i2]>=array[i1]){
                    l2++;
                }
                else{
                    l2++;
                    if(m2<l2){
                        m2=l2;
                        l2=0;
                    }
                    else{
                        l2=0;
                    }
                }
            }
            if(m2<l2){
                m2=l2;
            }
            // System.out.println(m1+" "+m2);
            count = m1+m2;
            if(maximum<=count){
                maximum=count;
            }

        }
        System.out.println(maximum);}

    }

    public static int max_sum(int[][] array,int i, int j,int n){
        // System.out.println(i+" "+j);
        if(i>n || j>n){
            // int sum = 0;
            return 0;
        }
        return array[i][j]+Math.max(max_sum(array,i+1,j,n),max_sum(array,i,j+1,n));
    }

    public static boolean isPrime(long num){
    if ( num > 2 && num%2 == 0 ) {
        // System.out.println(num + " is not prime");
        return false;
    }
    long top = (long)Math.sqrt(num) + 1;
    for(int i = 3; i < top; i+=2){
        if(num % i == 0){
            // System.out.println(num + " is not prime");
            return false;
        }
    }
    // System.out.println(num + " is prime");
    return true;
}

    public static BigInteger gcd(BigInteger a, BigInteger b)
    {
        BigInteger b1 = new BigInteger("0");
        // Everything divides 0
        if (a.equals(b1) || b.equals(b1))
           return b1;

        // base case
        if (a.equals(b))
            return a;

        // a is greater
        if (a.compareTo(b)==1)
            return gcd(a.subtract(b), b);
        return gcd(a, b.subtract(a));
    }

    // method to return LCM of two numbers
    public static BigInteger lcm(BigInteger a, BigInteger b)
    {

        return (a.multiply(b)).divide(gcd(a, b));
    }

    public static void filling2(long[] array1,long[] array,long[] aux,long mid){
        while(array1[0]<mid){
            aux[(int)array1[2]]=array[(int)array1[0]];
            array1[2]=array1[2]+1;
            array1[0]=array1[0]+1;
        }
    }

    public static boolean compare(long a, long b){
        if(a>b){
            return true;
        }else{
            return false;
        }
    }

    public static long modu(long n, long a, long b, long temp){
        long m = n/2;
        if(m<1){
            return 0;
        }else if(m>temp){
            return 0;
        }
        else{
            if(m%a==0 && m%b!=0 || m%b==0 && m%a!=0){
                return 1+modu(m-1,a,b,temp)+modu(m+1,a,b,temp);
            }else{
                return modu(m-1,a,b,temp)+modu(m+1,a,b,temp);
            }
        }
    }

    public static double distance(double a, double b, double c, double d){
        double d1 = (a-c)*(a-c);
        double d2 = (b-d)*(b-d);
        double d3 = d1+d2;
        double d4 = Math.sqrt(d3);
        return d4;
    }

    public static void merge(long[] array,long left,long mid,long right,long size,long[] aux){
        long[] array1 = new long[3];
        array1[0]=left;
        array1[1]=mid;
        array1[2]=left;
        long count=0;
        while((array1[0]<mid) && (array1[1]<right+1)){
            if(compare(array[(int)array1[0]],array[(int)array1[1]])){
                aux[(int)array1[2]]=array[(int)array1[1]];
                array1[2]=array1[2]+1;
                array1[1]=array1[1]+1;
                count+=mid-array1[0];
            }else{
                aux[(int)array1[2]]=array[(int)array1[0]];
                array1[2]=array1[2]+1;
                array1[0]=array1[0]+1;
            }
        }
        filling3(array1,array,aux,right);
        filling2(array1,array,aux,mid);
        filling1(array1,left,right,array,aux);
        // return count;
    }

    public static long weigh(long n){
        if(n<=30){
            return 40;
        }else if(n>30 && n<51){
            return 55;
        }else{
            if(n%50==0){
                long temp = n/50;
                long value = 25*(temp-1);
                return value+55;
            }else{
                long temp = n/50;
                temp++;
                // System.out.println(temp);
                long value = 25*(temp-1);
                return value+55;
            }
        }
    }

    public static long max_val(long[] array, int n, int start, int end){
        long maximum=0;
        long value1=array[0];
        long value2=0;
        int i=1;
        long result = looping(array,n,i,maximum,value1,value2);
        return result;
    }

    public static long max(long a , long b){
        if(a>b){
            return a;
        }else{
            return b;
        }
    }

    public static void counting(int[] array, int a, int b, int n){
            int indx1 = Binary(array,1,n,a);

            int indx2 = Binary(array,1,n,b);

            int diff = indx2-indx1;

            int result = diff+1;

            Result(result);
    }

    public static long result(long n, long m){
        long value = horse_path(n,m,1,1);
        return value;
    }

    public static int permutations(int n,int i, int count){
        while(i<n+1){
            int j=1;
            while(j<n+1){
                int prod = 0;
                prod = i*j;
                if(n%prod==0){
                    count++;
                }
                j++;
            }
            i++;
        }
        return count;
    }

    public static int swap2(int j1,int[] professor_list,int prof,int n){

                while(j1<n+1)
                {

                    if(professor_list[j1]==0){

                        prof=j1;

                        break;

                    }

                    j1++;

                }
                return prof;

    }

    public static boolean check(int[] array,int n, int sum, boolean boo, int max){
        int temp=max;
        boolean curr = boo;
        if(sum>0 && n==0){
            return false;
        }else if(sum==0){
            return true;
        }else if(array[n-1]>sum){
            return check(array,n-1,sum,curr,temp);
        }
        else{
            return check(array,n-1,sum,curr,temp) || check(array,n-1,sum-array[n-1],curr,temp);
        }
    }

    public static int swap4(int[] professor_list, int[] student_list, int prof, int stud, int total){

            professor_list[prof]=1;

            student_list[stud]=prof;

            total--;

            return total;

    }

    public static void show(int[] array,int n){

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

            System.out.println(i+" "+array[i]);

        }
    }

    public static int Binary(int[] array , int min, int max, int num){

        if(max<min){

            return -1;

        }

        else
        {

            int mid = min + (max-min)/2;

            if(array[mid]==num){

                return mid;

            }
            else if(array[mid]>num){

                return Binary(array,min,mid-1,num);

            }
            else
            {

                return Binary(array,mid+1,max,num);

            }
        }
    }

}


import java.util.*;
public class Main{
  public static long[] memo;
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int N = sc.nextInt();
    int[] h = new int[N];
    memo = new long[N];
    Arrays.fill(memo, -1L);
    for(int i = 0; i < N; i++){
      h[i] = sc.nextInt();
    }
    System.out.println(solve(h));
  }

  public static long solve(int[] array){
    long[] ans = new long[array.length];
    ans[0] = 0L;
    ans[1] = Math.abs(array[1] - array[0]);
    for(int i = 2; i < array.length; i++){
      long tmp1 = ans[i-1] + Math.abs(array[i] - array[i-1]);
      long tmp2 = ans[i-2] + Math.abs(array[i] - array[i-2]);
      ans[i] = Math.min(tmp1, tmp2);
    }
    return ans[array.length - 1];
  }
}


import java.util.Arrays;
import java.util.Scanner;

public class Main {
	static final int INF = Integer.MAX_VALUE;
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		int[] arr = new int[n];

		for(int i = 0 ; i < n ; ++i) {
			arr[i] = scan.nextInt();
		}

		int[] dp = new int[n];
		Arrays.fill(dp, INF);
		dp[0] = 0;
		dp[1] = Math.abs(arr[1] - arr[0]);
		for(int i = 2 ; i < n ; ++i) {
			dp[i] = Math.min(Math.abs(arr[i] - arr[i-1]) + dp[i-1], Math.abs(arr[i] - arr[i-2]) + dp[i-2]);
		}
		System.out.println(dp[n-1]);
	}
}


import java.util.*;
import java.io.*;

class Main {

     public static void main(String []args){
        FastReader sc = new FastReader();

        int n = sc.nextInt(), k = sc.nextInt();
        int [] heights = new int [n];
        for (int i = 0; i < n; i++) {
            heights[i] = sc.nextInt();
        }
        int [] dp = new int [n];

        for (int i = 1; i < n; i++) {
            dp[i] = dp[i - 1] + Math.abs(heights[i] - heights[i - 1]);
            for (int j = i - 2; j >= Math.max(0, i - k); j--) {
                dp[i] = Math.min(dp[i], dp[j] + Math.abs(heights[i] - heights[j]));
            }
        }

        System.out.println(dp[n - 1]);
     }

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

}

Score : 100 points

Problem Statement

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

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

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

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

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq K \leq 100

1 \leq h_i \leq 10^4

Input

Input is given from Standard Input in the following format:

N K
h_1 h_2 \ldots h_N

Output

Print the minimum possible total cost incurred.

Sample Input 1

5 3
10 30 40 50 20

Sample Output 1

30

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

Sample Input 2

3 1
10 20 10

Sample Output 2

20

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

Sample Input 3

2 100
10 10

Sample Output 3

0

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

Sample Input 4

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

Sample Output 4

40

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


import java.util.*;
import java.io.*;

public class Main {
	static int n = 0 , k = 0;
	static int a[] = new int[(int) 1e5 + 7];
	static int dp[] = new int[(int) 1e5 + 7];
	public static int fun(int ind) {
		if(ind == n-1) return 0;

		if(dp[ind] != -1) return dp[ind];

		else {
		         int max = (int) 1e5 + 7;

		         for(int i = 1; i<=k; i++) {
			          if(ind + i < n)
			              max = Math.min(max, Math.abs(a[ind + i] - a[ind]) + fun(ind + i));
		        }
		        return dp[ind] = max;
		}
	}
	public static void solve(InputReader in) {
		n = in.readInt();
		k = in.readInt();
        for(int i = 0; i<n; i++) {
        	a[i] = in.readInt();
        }
        Arrays.fill(dp, -1);
        System.out.println(fun(0));
	}
	public static void main(String[] args) {
		InputReader in = new InputReader(System.in);
		int t = 1;
		while(t-- > 0) {
			solve(in);
		}
	}
}

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 read() {
		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 int readInt() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			if (c < '0' || c > '9')
				throw new InputMismatchException();
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

     public String readString() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isSpaceChar(c));
		return res.toString();
	}

     public long readLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			if (c < '0' || c > '9') {
				throw new InputMismatchException();
			}
			res *= 10;
			res += c - '0';
			c = read();
		} 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 String next() {
		return readString();
	}

     public interface SpaceCharFilter {
		public boolean isSpaceChar(int ch);
	}
}


import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
  int n=sc.nextInt();
  int k=sc.nextInt();
  int arr[]=new int[n];
  for(int i=0;i<n;i++)
    arr[i]=sc.nextInt();

  int sto[]=new int[n];
  for(int i=0;i<n;i++)
    sto[i]=Integer.MAX_VALUE;
  sto[0]=arr[0];
  for(int i=1;i<n;i++){
  for(int j=i-1;j>=1 ;j--){
    sto[i]=Math.min(sto[i],sto[j]+Math.abs(arr[i]-arr[j]));
  }
  }
  System.out.println(sto[n-1]);
}

}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] h = new int[n];
        for (int i = 0; i < n; i++) {
            h[i] = sc.nextInt();
        }

        int[] dp = new int[n];
        for (int i = 0; i < n; i++) {
            dp[i] = Integer.MAX_VALUE;
        }

        dp[0] = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= k; j++) {
                int a = dp[i + j] + Math.abs(h[i] - h[i + j]);
                if (dp[i] > a) {
                    dp[i] = a;
                }
            }
        }

        System.out.println(dp[n - 1]);
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.*;

// import
class Main {

    static int min(int a,int b)
    {
        return Math.min(a, b);
    }

    static int abs(int a)
    {
        return Math.abs(a);
    }

    public static void main(String[] args) throws Exception {
        PrintWriter p = new PrintWriter(System.out);
        // Scanner sc = new Scanner(System.in);
        // int n = sc.nextInt();
        // sc.nextLine();
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

        Object[] nk =Arrays.stream(bf.readLine().split(" ")).map(Integer::parseInt).toArray();

        int n = (int)nk[0];
        int k = (int)nk[1];

        Integer arr[] = Arrays.stream(bf.readLine().split(" ")).map(Integer::parseInt).toArray(Integer[]::new);

        int dp[] = new int[n+1];
        // int mod = 100000000+7;
        Arrays.fill(dp, Integer.MAX_VALUE); //fill large values in dp
        dp[0] = 0;
        for (int i = 0; i < n; i++)
        {
            for (int j = 1; j <= k; j++)
            {
                if(i+j< n) dp[i+j] = min(dp[i+j],dp[i]+abs(arr[i]-arr[i+j]));
            }
        }
        // System.out.println(Arrays.toString(dp));
        // System.out.println(dp[n-1]);
        p.println(dp[n-1]);
        p.flush();
    }
}


import java.util.Arrays;
import java.util.Scanner;

public class Main {

    void run() {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] hArr = new int[n + 1000];
        for (int i = 0; i < n; i++) {
            hArr[i] = sc.nextInt();
        }

        int[] dp = new int[n + 1000];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 1; j <= k; j++) {
                dp[i + j] = Math.min(dp[i + j], dp[i] + Math.abs(hArr[i] - hArr[i + j]));
            }
        }
        //debug(dp);
        System.out.println(dp[n - 1]);
    }

    void debug(Object... os) {
        System.err.println(Arrays.deepToString(os));
    }

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


import java.util.*;
import java.io.*;
import java.math.*;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int k = sc.nextInt();
    int[] nums = new int[n];
    int[] dp = new int[n];
    for (int i = 0; i < n; i++) {
      nums[i] = sc.nextInt();
    }
    Arrays.fill(dp, 1000000);
    dp[0] = 0;
    for (int i = 1; i < n; i++) {
      for (int j = 1; j <= k; j++) {
        if (i >= j) {
          dp[i] = Math.min(dp[i], dp[i - j] + Math.abs(nums[i] - nums[i - j]));
        }
      }
    }
    System.out.println(dp[n - 1]);
  }
}


import java.util.*;
import java.io.*;
import java.math.BigInteger;

public class Main {
	static PrintWriter out;
	static StringBuilder sb;
	static final double EPS = 1e-9;
	static long mod = (int) 1e9 + 7;
	static int inf = (int) 1e9 + 2;
	static long[] fac;
	static int[] si;
	static ArrayList<Integer> primes;
	static ArrayList<Integer>[] ad;
	static ArrayList<pair>[] d;
	static edge[] ed;
	static boolean []vis;
	static int[] l, ch;
	static int[] occ;
	static Queue<Integer>[] can;
	static String s;
	static int n,m;
	static long []memo;
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		out = new PrintWriter(System.out);
	    n=sc.nextInt();
	    int k=sc.nextInt();
	    memo=new long [n];
	    long []a=new long [n];
	    for(int i=0;i<n;i++)
	    	a[i]=sc.nextLong();
	    Arrays.fill(memo, Long.MAX_VALUE);
	    memo[n-1]=0;
	    for(int i=n-2;i>=0;i--) {
	    	for(int j=1;j<=k;j++) {
	    		if(i+j>n-1)
	    			break;
	    		memo[i]=Math.min(memo[i], memo[j+i]+Math.abs(a[i]-a[j+i]));
	    	}
	    }
	    out.print(memo[0]);
		out.flush();
	}
	static long inver(long x,long kk) {
		int a = (int) x;
		long e = (kk - 2);
		long res = 1;
		while (e > 0) {
			if ((e & 1) == 1) {
				// System.out.println(res*a);
				res = (int) ((1l * res * a) % kk);
			}
			a = (int) ((1l * a * a) % kk);
			e >>= 1;
		}
		// out.println(res+" "+x);
		return res % kk;
	}

	static TreeSet<Integer> trr;

	static class qu  implements Comparable<qu>{
		int i,j;
		qu(int a, int s) {
			i=a;
			j=s;
		}
       public String toString() {
    	   return i+" "+j;
       }
       public int compareTo(qu o) {
    	   if(i==o.i)
    		   return j-o.j;
    	   return i-o.i;
       }
	}

	static class pair {
		int to;
		int number;

		pair(int t, int n) {
			number = n;
			to = t;
		}

		public String toString() {
			return to + " " + number;
		}
	}

	static double modPow(double a, int e)

	{
		double res = 1;
		while (e > 0) {
			if ((e & 1) == 1)
				res = (res * a);
			a = (a * a);
			e >>= 1;
		}
		return res;
	}

	static boolean[] in;

	/*
	 * static void mst() { Arrays.sort(ed); UnionFind uf=new UnionFind(n); for(int
	 * i=0;i<m;i++) { edge w=ed[i]; if(!uf.union(w.from, w.to)) continue;
	 * in[i]=true; } }
	 */
	static class edge implements Comparable<edge> {
		int from;
		int to;
		int number;

		edge(int f, int t, int n) {
			from = f;
			to = t;
			number = n;
		}

		public String toString() {
			return from + " " + to + " " + number;
		}

		public int compareTo(edge f) {
			return number - f.number;
		}
	}

	static class seg implements Comparable<seg> {
		int a;
		int b;

		seg(int s, int e) {
			a = s;
			b = e;
		}

		public String toString() {
			return a + " " + b;
		}

		public int compareTo(seg o) {
			// if(a==o.a)
			return o.b - b;
			// return
		}
	}

	static long power(int i) {
		// if(i==0)
		// return 1;
		long a = 1;
		for (int k = 0; k < i; k++)
			a *= i;
		return a;
	}

	static void seive(int N) {
		si = new int[N];
		primes = new ArrayList<>();
		si[1] = 1;
		for (int i = 2; i < N; i++) {
			if (si[i] == 0) {
				si[i] = i;
				primes.add(i);
			}
			for (int j = 0; j < primes.size() && primes.get(j) <= si[i] && (i * primes.get(j)) < N; j++)
				si[primes.get(j) * i] = primes.get(j);

		}
	}
	static long fac(int n) {
		if (n == 0)
			return fac[n] = 1;
		if (n == 1)
			return fac[n] = 1;
		long ans = 1;
		for (int i = 1; i <= n; i++)
			fac[i] = ans = (i % mod * ans % mod) % mod;
		return ans % mod;
	}

	static long gcd(long a, long b) {

		if (b == 0)
			return a;
		return gcd(b, a % b);
	}

	static class unionfind {
		int[] p;
		int[] size;

		unionfind(int n) {
			p = new int[n];
			size = new int[n];

			for (int i = 0; i < n; i++) {
				p[i] = i;
			}
			Arrays.fill(size, 1);
		}

		int findSet(int v) {
			if (v == p[v])
				return v;
			return p[v] = findSet(p[v]);
		}

		boolean sameSet(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			return false;
		}

		int max() {
			int max = 0;
			for (int i = 0; i < size.length; i++)
				if (size[i] > max)
					max = size[i];
			return max;
		}

		boolean combine(int a, int b) {
			a = findSet(a);
			b = findSet(b);
			if (a == b)
				return true;
			if (size[a] > size[b]) {
				p[b] = a;
				size[a] += size[b];

			} else {
				p[a] = b;
				size[b] += size[a];
			}
			return false;
		}
	}

	static class Scanner {
		StringTokenizer st;
		BufferedReader br;

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

		public Scanner(String file) throws Exception {
			br = new BufferedReader(new FileReader(file));
		}

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

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

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

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

		public char nextChar() throws IOException {
			return next().charAt(0);
		}

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

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

		public void waitForInput() throws InterruptedException {
			Thread.sleep(3000);
		}
	}
}


import java.util.*;

class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int k = in.nextInt();
		int[] a = new int[n];
		int[] h = new int[n];
		for(int i=0;i<n;i++) {
			h[i] = in.nextInt();
		}
		for(int i=0;i<n;i++) {
			a[i] = Integer.MAX_VALUE;
		}
		a[0] = 0;
		for(int i=0;i<n;i++) {
			for(int j=1;j<=k&&i+j<n;j++) {
				a[i+j] = Math.min(a[i+j], a[i]+Math.abs(h[i]-h[i+j]));
			}
		}
		System.out.println(a[n-1]);
	}
}


import java.util.*;
public class Main{
    static long[] dp = new long[1000000];
	public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        Arrays.fill(dp, Long.MAX_VALUE);
        dp[0] = 0;

        int n = sc.nextInt();
        int k = sc.nextInt();
        int h[] = new int[n+100];

        for(int i=0; i<n; i++) h[i] = sc.nextInt();

        dp[1] = Math.abs(h[0]-h[1]);
        for(int i=0; i<n; i++){
            for(int j=1; j<=k; j++)
            dp[i+j] = Math.min(dp[i+j],dp[i]+Math.abs(h[i]-h[i+j]));
        }
        System.out.println(dp[n-1]);

    }

}