Divide Array Into Increasing Sequences Problem
Description
LeetCode Problem 1121.
Given an integer array nums sorted in non-decreasing order and an integer k, return true if this array can be divided into one or more disjoint increasing subsequences of length at least k, or false otherwise.
Example 1:
Input: nums = [1,2,2,3,3,4,4], k = 3
Output: true
Explanation: The array can be divided into two subsequences [1,2,3,4] and [2,3,4] with lengths at least 3 each.
Example 2:
Input: nums = [5,6,6,7,8], k = 3
Output: false
Explanation: There is no way to divide the array using the conditions required.
Constraints:
1 <= k <= nums.length <= 10^51 <= nums[i] <= 10^5numsis sorted in non-decreasing order.
Solution
Approach: Count the Most Frequent Value
A strictly increasing subsequence cannot use the same value twice. So if the most frequent value appears most times, every copy of it sits in a different subsequence, and we need at least most subsequences. Each one needs at least k numbers, so most * k <= n is necessary.
It is also enough. Number the elements 0, 1, ..., n - 1 in sorted order and put element i into subsequence i % most. Equal values are consecutive in the array and there are at most most of them, so they land in different subsequences, which makes each one strictly increasing. Each subsequence gets at least floor(n / most) elements, and most * k <= n means that is at least k.
Because nums is sorted, equal values form runs, so most is just the longest run: one scan, no hash map. Watch the product: most * k can be as large as 10^10, so compute it with 64-bit integers in Java and C++.
Complexity: O(n) time and O(1) extra space.
class Solution:
def canDivideIntoSubsequences(self, nums: List[int], k: int) -> bool:
# Equal values sit next to each other, so the most frequent value is the longest run.
most = run = 0
for i, x in enumerate(nums):
run = run + 1 if i > 0 and nums[i - 1] == x else 1
most = max(most, run)
# Each copy of it needs its own subsequence, and each subsequence needs k numbers.
return most * k <= len(nums)