Statementâ–¼
Given a sorted integer array, nums
, in non-decreasing order and an integer, k
, determine whether it is possible to partition the array into one or more disjoint increasing subsequences, each having a length of at least k
. Return true
if such a partition exists; otherwise, return false
.
Constraints:
1≤ k
≤ nums.length
≤103 1≤ nums[i]
≤103 The
nums
array is sorted in non-decreasing order.
Solution
The essence of this solution lies in determining whether the array has enough elements to accommodate the most frequently occurring number across multiple subsequences of at least length k
. If the array doesn’t contain any duplicates, the entire array can form an increasing subsequence. Otherwise, duplicate numbers appear consecutively as the array is sorted, allowing us to track their frequency and record the maximum frequency. For a valid division, the total number of elements in nums
must be at least k * max_freq
. This is because once we ensure the most frequent number can be evenly distributed across subsequences of at least length k
, the remaining numbers will naturally fit into the sequences without issue.
Using the intuition above, we implement the algorithm as follows:
Initialize a variable,
curr_freq
, to track the count of consecutive occurrences of the same number.Initialize another variable,
max_freq
, to store the maximum frequency of any element, i.e., the highest count of any repeated element innums
.Iterate through
nums
, starting from the second element:If the current element is equal to the previous one (
nums[i - 1]
== nums[i]
), incrementcurr_freq
to count consecutive occurrences of the same number.Otherwise, reset
curr_freq
to1
, indicating a new number starts.Update
max_freq
to store the maximum count of any repeating number found so far.
Return TRUE if the total number of elements in
nums
is at leastk * max_freq
; otherwise, return FALSE.
Let’s look at the following illustration to get a better understanding of the solution: