牛客网 2018校招真题 网易 疯狂队列

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32767041/article/details/86485941

Description

牛客网 2018校招真题 疯狂队列

Solving Ideas

贪心,数组排序后,交叉地将最小元素和最大元素插入到疯狂队列中,使疯狂队列向两边扩展。

Solution

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

/**
 * @author wylu
 */
public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int[] h = new int[n];
        String[] strs = br.readLine().split(" ");
        for (int i = 0; i < n; i++) {
            h[i] = Integer.parseInt(strs[i]);
        }

        Arrays.sort(h);

        int min = h[0], max = h[n - 1];
        int sum = max - min;
        int i = 1, j = n - 2;
        while (i < j) {
            sum += max - h[i];
            sum += h[j] - min;
            min = h[i++];
            max = h[j--];
        }
        sum += Math.max(h[j] - min, max - h[i]);
        System.out.println(sum);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_32767041/article/details/86485941