[LeetCode] Maximum Number of Groups With Increasing Length

2790. Maximum Number of Groups With Increasing Length

You are given a 0-indexed array usageLimits of length n.

Your task is to create groups using numbers from 0 to n - 1, ensuring that each number, i, is used no more than usageLimits[i] times in total across all groups. You must also satisfy the following conditions:

  • Each group must consist of distinct numbers, meaning that no duplicate numbers are allowed within a single group.
  • Each group (except the first one) must have a length strictly greater than the previous group.

Return an integer denoting the maximum number of groups you can create while satisfying these conditions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
bool helper(vector<int>& A, int k) {
int need = 0, x = k;
for(int i = A.size() - 1; i >= 0; i--,x = max(x - 1, 0)) {
if(A[i] == x) continue;
if(A[i] > x) {
int now = A[i] - x;
need = max(0, need - now);
} else {
need += x - A[i];
}

}
return need == 0;
}
public:
int maxIncreasingGroups(vector<int>& A) {
sort(begin(A), end(A));
int l = 0, r = A.size(), res = l;
while(l <= r) {
int m = l + (r - l) / 2;
bool ok = helper(A, m);
if(ok) {
res = max(res, m);
l = m + 1;
} else r= m - 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/23/PS/LeetCode/maximum-number-of-groups-with-increasing-length/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.