LeetCode-2790 长度递增组的最大数目
Table of Contents
LeetCode-2790 长度递增组的最大数目 #
Solution 1 #
二分搜索答案. 考虑从大到小排序后的数组与目标数组的差异, 注意前面少的可以用后面多的补.
using ll = long long;
class Solution {
public:
int maxIncreasingGroups(vector<int>& usageLimits) {
sort(usageLimits.begin(), usageLimits.end(), greater<int>());
auto check = [&](int m) {
int res = 0;
for (int i = 0; i < usageLimits.size(); i++) {
res = min(res + usageLimits[i] - max(m - i, 0), 0);
}
return res >= 0;
};
ll left = 2, right = usageLimits.size() + 1;
while (left < right) {
ll mid = left + (right - left) / 2;
if (check(mid)) {
left = mid + 1;
}
else {
right = mid;
}
}
return left - 1;
}
};
Solution 2 #
考虑如下的构造方法:
- 考虑一个形如上三角矩阵的网格, 我们从数量小的数字开始填格子;
- 前 $k$ 行至多形成 $k$ 组, 需要 $\frac{k(k+1)}{2}$ 个数字;
- 统计数字数量是否够就可以.
这种构造方法的精妙之处在于, 从数量小的数字开始填, 详细的思路讲解参见0x3f的周赛讲解:证明题?构造题!【力扣周赛 355】
using ll = long long;
class Solution {
public:
int maxIncreasingGroups(vector<int>& usageLimits) {
sort(usageLimits.begin(), usageLimits.end());
ll res = 0, ans = 0;
for (int v: usageLimits) {
res += v;
if (res >= (ans + 1) * (ans + 2) / 2) {
ans++;
}
}
return ans;
}
};