LeetCode in Kotlin

1838. Frequency of the Most Frequent Element

Medium

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.

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:

Example 3:

Input: nums = [3,9,6], k = 2

Output: 1

Constraints:

Solution

class Solution {
    fun maxFrequency(nums: IntArray, k: Int): Int {
        countingSort(nums)
        var start = 0
        var preSum = 0
        var total = 1
        for (i in nums.indices) {
            var length = i - start + 1
            var product = nums[i] * length
            preSum += nums[i]
            while (product - preSum > k) {
                preSum -= nums[start++]
                length--
                product = nums[i] * length
            }
            total = total.coerceAtLeast(length)
        }
        return total
    }

    private fun countingSort(nums: IntArray) {
        var max = Int.MIN_VALUE
        for (num in nums) {
            max = max.coerceAtLeast(num)
        }
        val map = IntArray(max + 1)
        for (num in nums) {
            map[num]++
        }
        var i = 0
        var j = 0
        while (i <= max) {
            if (map[i]-- > 0) {
                nums[j++] = i
            } else {
                i++
            }
        }
    }
}