1838. Frequency of the Most Frequent Element
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
요소의 빈도는 배열에서 발생하는 횟수입니다.
정수 배열 nums와 정수 k가 주어집니다. 한 작업에서 nums의 인덱스를 선택하고 해당 인덱스의 요소를 1씩 증가시킬 수 있습니다.
최대 k개의 작업을 수행한 후 요소의 최대 가능한 빈도를 반환합니다.
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:
- 1 <= nums.length <= 10^5
- 1 <= nums[i] <= 10^5
- 1 <= k <= 10^5
코드
class Solution {
fun maxFrequency(nums: IntArray, k: Int): Int {
nums.sort()
var l = 0
var r = 0
var answer = 0
var sum = 0L
while (r < nums.size) {
sum += nums[r].toLong()
while (nums[r].toLong() * (r - l + 1) - sum > k) {
sum -= nums[l].toLong()
l++
}
answer = maxOf(answer, r - l + 1)
r++
}
return answer
}
}
'LeetCode > Sliding Window' 카테고리의 다른 글
[LeetCode][Kotlin] 930. Binary Subarrays With Sum (0) | 2024.11.15 |
---|---|
[LeetCode][Kotlin] ⭐️ 658. Find K Closest Elements (0) | 2024.11.09 |
[LeetCode][Kotlin] 567. Permutation in String (0) | 2024.11.07 |