一、题目
输入
10
7334774857 8461862436 540886577 5245195052 9194400521 5412986878 6694133363 1186771950 1405713915 7115286932输出
-29430338967
二、思考
构造差分数组:C[i] = A[i+1] - A[i]
由题目条件可知:当A[i] = A[i+1] + A[i-1] - A[i]时:
C[i](现) = A[i+1] - A[i](现) = A[i] - A[i-1]
C[i-1](现)= A[i](现) - A[i-1] = A[i+1] - A[i]
得出结论:做一次题目中的操作,例如,修改A[i]就会交换差分数组中C[i-1]和C[i]两个的顺序而数组和为A[0]+A[1]+....+A[n-1] = A[0] + (A[0] + C[0](现)) + (A[0] + C[0](现) + C[1](现)).......所以差分数组越前面的项被加的次数越多,要使数组的和最小,差分数组就要按小到大排列
三、代码
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextLong();
}
long[] c = new long[n - 1];
for (int i = 0; i < n - 1; i++)
c[i] = a[i + 1] - a[i];
Arrays.sort(c);
long sum = a[0];
for (int i = 1; i < n; i++) {
a[i] = a[i - 1] + c[i - 1];
sum += a[i];
}
System.out.println(sum);
}
}