n, m = map(int, input().split()) a = list(map(int, input().split())) a,min1 = sorted(a), float('inf') for i in range(n-m+1): x,y = a[i],a[i+m-1] shu = y**2-x**2 if shu < min1: min1 = shu print(min1)
##此题看似很难,但是我们在做这种题的时候,都一定是转化为单循环,双循环必超时,由于不和谐度与数之间的差值和和有关,因为x平方减y平方等于x与y的和乘以x与y的差,所以xy应该尽量小,且差值也应该小,所以此时可以直接sorted,之后可以发现,因为排序后Bi的值一直在增大,所以可以去掉绝对值,所以化简成了最后一个数的平方减去第一个数的平方,由此转化成了单循环
import java.util.*; import java.io.*; // 定长滑动窗口统计满足条件的最小区间值 public class Main { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String[] line1 = bf.readLine().split(" "); int n = Integer.parseInt(line1[0]); int m = Integer.parseInt(line1[1]); int[] str = Arrays.stream(bf.readLine().split(" ")).mapToInt( Integer::parseInt).toArray(); Arrays.sort(str); long minL = 0; //注意精度问题,L超过21亿的范围 //第一个窗口的minL for (int i = 1; i < m; i++) { minL += Math.pow(str[i], 2) - Math.pow(str[i - 1], 2); } //定长窗口的L long conL = minL; for (int r = m; r < n; r++) { //注意精度损失,int*int结果仍为int,会有损失。pow内隐式转换int为double不会损失。 //新增元素r的L大小控制变化 conL += Math.pow(str[r], 2) - Math.pow(str[r - 1], 2); //减少元素r-m的L大小控制变化 conL -= Math.pow(str[r - m + 1], 2) - Math.pow(str[r - m], 2); if (conL < minL) { minL = conL; } } System.out.println(minL); } }