题解 | 画展布置

画展布置

https://www.nowcoder.com/practice/4082da66f6034a1d9b6a7206e1d0445a

import java.util.*;
import java.math.BigInteger;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int M = in.nextInt();
        int[] A = new int[N];
        for (int i = 0; i < N; i++) A[i] = in.nextInt();
        Arrays.sort(A);
        BigInteger L =  BigInteger.valueOf(Long.MAX_VALUE);
        BigInteger curL = BigInteger.valueOf(0);
        //初始化第一个区间
        int l = 0;
        int r = M - 1;
        for (int i = l; i < r; i++) {
            curL = curL.add(sq(A[i + 1]).subtract(sq(A[i])));
        }
        if (L.compareTo(curL) > 0)
            L = curL;
        //遍历剩余区间
        for (l = 1; l <= N - M; l++) {
            //移除l-1与l的差
            //新增l+M-1与l+M-2的差
            curL = curL .subtract(sq(A[l]).subtract(sq(A[l - 1])));
            curL = curL .add (sq(A[l + M - 1]).subtract(sq(A[l + M - 2])));
            if (L.compareTo(curL) > 0)
                L = curL;
        }
        System.out.println(L);
    }
    private static BigInteger sq(long num) {
        BigInteger res = BigInteger.valueOf(num);
        return res.multiply(res);
    }
}

全部评论

相关推荐

看起来名字可以很长:笑死 我暑期实习阿里云的意向也被 qq 邮箱放在垃圾箱了
点赞 评论 收藏
分享
12-05 18:09
已编辑
广东药科大学 后端工程师
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务