暴力解法:记录删除掉a1 ... an-1后的每一个数组的最大间隔,取最小值
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
//保存所有情况下的最大间隔
List<Integer> ans = new ArrayList<>();
for (int i = 1; i < n - 1; i++) {
//获取删除掉当前元素后的数组
List<Integer> curList = removeList(arr, i);
int maxDiff = 0;//记录此时数组的最大间隔
for (int j = 1; j < curList.size(); j++) {
int diff = curList.get(j) - curList.get(j - 1);
maxDiff = Math.max(maxDiff, diff);
}
ans.add(maxDiff);
}
//此时ans中记录了所有情况下的最大间隔,找到最小值即可
Collections.sort(ans);
System.out.println(ans.get(0));
}
}
//获取删除掉某一个元素后的数组
public static List<Integer> removeList(int[] arr, int index) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
if (i == index) continue;
res.add(arr[i]);
}
return res;
}
}