输入包括两行,第一行一个整数n(1 ≤ n ≤ 50),表示学生的人数 第二行为n个整数h[i](1 ≤ h[i] ≤ 1000),表示每个学生的身高
输出一个整数,表示n个学生列队可以获得的最大的疯狂值。 如样例所示: 当队列排列顺序是: 25-10-40-5-25, 身高差绝对值的总和为15+30+35+20=100。 这是最大的疯狂值了。
5 5 10 25 40 25
100
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { int n = sc.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++){ a[i] = sc.nextInt(); } Arrays.sort(a); int res = 0, left = 1, right = n - 2; int min_value = a[0]; int max_value = a[n - 1]; res += Math.abs(a[0] - a[n - 1]); while (left <= right) { if (left == right) { //此时表示只剩一个元素(即数组长度为奇数) res += Math.max(Math.abs(a[left++] - max_value), Math.abs(a[right--] - min_value)); } else { res += Math.abs(a[left] - max_value); res += Math.abs(a[right] - min_value); min_value = a[left++]; max_value = a[right--]; } } System.out.println(res); } sc.close(); } }