LeetCode 1121. Divide Array Into Increasing Subsequences
原题链接
困难
作者:
JasonSun
,
2020-01-24 06:04:51
,
所有人可见
,
阅读 1437
Algorithm (Counter)
- Let $n$ denote the length of $\texttt{nums}$ and $m$ be the maximum duplicate count of
nums
. In order to the divided subsequences to be disjoint and each has length at least $K,$ we would require $n\geq mK.$
- We show that this is in fact also a sufficient condition constructively as follows: we create $m$ buckets $B_{i}$ and assign
num[i]
to $B_{i\mod m}$. It is easy to see that $B_{i}$’s will form sequences that are disjoint.
Code
class Solution {
public:
bool canDivideIntoSubsequences(vector<int>& nums, int K) {
const auto max_duplicate = [&] {
const auto counter = [&](unordered_map<int, int> self = {}) {
for (const auto x : nums)
self[x]++;
return self;
}();
const auto [val, count] = *max_element(begin(counter), end(counter), [&](const auto &x, const auto &y) {
return x.second < y.second;
});
return count;
}();
const auto solution = size(nums) >= max_duplicate * K;
return solution;
}
};