2024/10/27 灵茶题单 不定长滑动窗口

This commit is contained in:
Cool 2024-10-27 22:58:18 +08:00
parent 89f34adbdc
commit faeab03adb
1 changed files with 42 additions and 0 deletions

View File

@ -0,0 +1,42 @@
package com.cool.ling_cha_mount.sliding_windows;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/10/27/22:48
* @Description:
*/
public class Num1838 {
public int maxFrequency(int[] nums, int k) {
Arrays.sort(nums);
long l= k;
long left = 0;
long res = 1;
for (int i = 1; i < nums.length; i++) {
l -=(nums[i] - nums[i - 1]) *(i - left);
while (l < 0) {
l += nums[i] - nums[(int)left++];
}
res = Math.max(res, i - left + 1);
}
return (int)res;
}
public int maxFrequency1(int[] nums, int k) {
Arrays.sort(nums);
int left = 0, res = 1;
long total = 0;
for (int i = 0; i < nums.length; i++) {
total += nums[i];
while ((long) nums[i] * (i - left + 1) - total > k) {
total -= nums[left];
left++;
}
res = Math.max(res, i - left + 1);
}
return res;
}
}