思路:排序+计算贡献
step1:对于x,每有一个y < x , 那么贡献就是x - y
那么x的所有贡献就是 v * x - sum(y) , 其中v是小于x的数的个数,sum(y)是所有小于x的数的和。
step2:考虑排序,然后sum(y)就是一个前缀和,v也可以通过数的下标快速得到。直接枚举每个数进行计算即可。
具体细节看代码
代码实现
def main():
n = int(input())
a = list(map(int, input().split()))
s = sum(a)
ans = 0
a.sort()
for i in range(n):
s -= a[i]
ans += s - a[i] * (n - i - 1)
print(ans)
if __name__ == "__main__":
main()
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int arraySize = scanner.nextInt(); // 读取数组大小
int[] numbers = new int[arraySize]; // 创建数组
long totalSum = 0, result = 0; // 初始化总和和结果
// 读取输入值并计算总和
for (int index = 0; index < arraySize; index++) {
numbers[index] = scanner.nextInt(); // 读取每个数字
totalSum += numbers[index]; // 累加总和
}
// 对数组进行排序
Arrays.sort(numbers);
// 基于排序后的数组计算结果
for (int index = 0; index < arraySize; index++) {
totalSum -= numbers[index]; // 减去当前数字
result += totalSum - (long) numbers[index] * (arraySize - index - 1); // 计算结果
}
// 输出最终结果
System.out.println(result);
}
}