给你一个整数数组 nums 和一个整数 k 。在一步操作中,你可以选择 nums 的一个下标,并将该下标对应元素的值增加 1 。执行最多 k 次操作后,返回数组中最高频元素的 最大可能频数(n<1e5)
思路:二分距离当前位置 i 前面,可以最大变换的连续数的个数
func maxFrequency(A []int, k int) int {
sort.Ints(A)
n, ans := len(A), 0
s := make([]int, n+1)
for i := 1; i <= n; i++ {
s[i] = s[i-1] + A[i-1]
}
for i := 1; i <= n; i++ {
l, r := 1, i
for l < r {
m := (l + r) / 2
if A[i-1] * (i - m + 1) - (s[i] - s[m-1]) <= k { //将a[m...i-1]这一段元素变为a[i]的代价
r = m
} else {
l = m + 1
}
}
if i - r + 1 > ans {
ans = i - r + 1
}
}
return ans
}