LeetCode in Kotlin

3659. Partition Array Into K-Distinct Groups

Medium

You are given an integer array nums and an integer k.

Your task is to determine whether it is possible to partition all elements of nums into one or more groups such that:

Return true if such a partition is possible, otherwise return false.

Example 1:

Input: nums = [1,2,3,4], k = 2

Output: true

Explanation:

One possible partition is to have 2 groups:

Each group contains k = 2 distinct elements, and all elements are used exactly once.

Example 2:

Input: nums = [3,5,2,2], k = 2

Output: true

Explanation:

One possible partition is to have 2 groups:

Each group contains k = 2 distinct elements, and all elements are used exactly once.

Example 3:

Input: nums = [1,5,2,3], k = 3

Output: false

Explanation:

We cannot form groups of k = 3 distinct elements using all values exactly once.

Constraints:

Solution

import kotlin.math.max

class Solution {
    fun partitionArray(nums: IntArray, k: Int): Boolean {
        val n = nums.size
        if (n % k != 0) {
            return false
        }
        var max = 0
        for (x in nums) {
            max = max(max, x)
        }
        val count = IntArray(max + 1)
        val limit = n / k
        for (x in nums) {
            if (++count[x] > limit) {
                return false
            }
        }
        return true
    }
}