算法思想
维护前缀和和后缀和,然后减去左边选中数字乘上左边个数减去左前缀和,右边前缀和减去选中数字乘上右边个数
时间复杂度
O(n)
java 代码
//维护前缀和和后缀和,然后减去左边选中数字乘上左边个数减去左前缀和,右边前缀和减去选中数字乘上右边个数
//时间复杂度O(n)
import java.io.*;
import java.lang.*;
import java.util.*;
class Main{
static int n = 0, N = 100010;
static int[] nums = new int[N];
static int[] pre = new int[N];
static int[] end = new int[N];
public static void main(String[] args)throws Exception{
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
n = Integer.valueOf(buf.readLine());
String[] info = buf.readLine().split(" ");
for(int i = 1; i <= n; ++i){
nums[i] = Integer.valueOf(info[i - 1]);
}
Arrays.sort(nums, 1, n + 1);
for(int i = 1; i <= n; ++i){
pre[i] = pre[i - 1] + nums[i];
end[n + 1 - i] = end[n + 2 - i] + nums[n + 1 - i];
}
int min = 0x3f3f3f3f;
for(int i = 1; i <= n; ++i){
int w = nums[i] * (i - 1) - pre[i - 1] + end[i + 1] - nums[i] * (n - i);
min = Math.min(min, w);
}
System.out.print(min);
}
}