Divide Array Into Increasing Sequences

hard array counting hash map

Problem

Given a sorted (non-decreasing) array nums and an integer k, decide whether nums can be partitioned into one or more disjoint strictly increasing subsequences, each of length at least k. Return true if such a partition exists.

Inputnums = [1, 2, 2, 3, 3, 4, 4], k = 3
Outputtrue
The most frequent value appears 2 times, so we need 2 subsequences. With 7 elements, 2 × 3 = 6 ≤ 7, so it fits: e.g. [1,2,3,4] and [2,3,4].

def can_divide_into_subsequences(nums, k):
    n = len(nums)
    max_freq = 1
    cur = 1
    for i in range(1, n):
        if nums[i] == nums[i - 1]:
            cur += 1
            max_freq = max(max_freq, cur)
        else:
            cur = 1
    return max_freq * k <= n
function canDivideIntoSubsequences(nums, k) {
  const n = nums.length;
  let maxFreq = 1, cur = 1;
  for (let i = 1; i < n; i++) {
    if (nums[i] === nums[i - 1]) {
      cur++;
      maxFreq = Math.max(maxFreq, cur);
    } else {
      cur = 1;
    }
  }
  return maxFreq * k <= n;
}
class Solution {
    public boolean canDivideIntoSubsequences(int[] nums, int k) {
        int n = nums.length;
        int maxFreq = 1, cur = 1;
        for (int i = 1; i < n; i++) {
            if (nums[i] == nums[i - 1]) {
                cur++;
                maxFreq = Math.max(maxFreq, cur);
            } else {
                cur = 1;
            }
        }
        return (long) maxFreq * k <= n;
    }
}
bool canDivideIntoSubsequences(vector<int>& nums, int k) {
    int n = (int)nums.size();
    int maxFreq = 1, cur = 1;
    for (int i = 1; i < n; i++) {
        if (nums[i] == nums[i - 1]) {
            cur++;
            maxFreq = max(maxFreq, cur);
        } else {
            cur = 1;
        }
    }
    return (long long)maxFreq * k <= n;
}
Time: O(n) Space: O(1)