import java.util.*;

public class Main {
	static int[] a;
	static long k;
	static int n;
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextLong();
		a = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
		}
		Arrays.sort(a);
		long l = a[0], r = a[0] + k; // 最大可能的最小数
		while (l < r) {
			long mid = (l + r + 1) / 2;
			if (check(mid)) l = mid;
			else r = mid - 1;
		}
		System.out.println(l);
	}
	
	static boolean check(long mid) {
		long s = k;
		for (int i = 0; i < n; i++) {
			s -= mid - a[i];
			if (s < 0) return false;
		}
		return true;
	}
}

这题先排序,然后得到最大可能的最小值a[0]+k,然后二分L=a[0],R=a[0]+k去查找,每次查找都遍历a数组,判断k次操作消耗完时,最大的最小值是否等于当前二分查找的mid值,若k次操作后最大的最小值无法达到当前查找的值(s<0),则return false,往更小的值去查找,最后L上的值就为最大的最小数了。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐