Skip to content

2790. Maximum Number of Groups With Increasing Length 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int maxIncreasingGroups(vector<int>& usageLimits) {
    int ans = 1;  // the next target length
    long availableLimits = 0;

    ranges::sort(usageLimits);

    for (const int usageLimit : usageLimits) {
      availableLimits += usageLimit;
      // Can create groups 1, 2, ..., ans.
      if (availableLimits >= ans * static_cast<long>(ans + 1) / 2)
        ++ans;
    }

    return ans - 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int maxIncreasingGroups(List<Integer> usageLimits) {
    int ans = 1; // the next target length
    long availableLimits = 0;

    Collections.sort(usageLimits);

    for (final int usageLimit : usageLimits) {
      availableLimits += usageLimit;
      // Can create groups 1, 2, ..., ans.
      if (availableLimits >= ans * (long) (ans + 1) / 2)
        ++ans;
    }

    return ans - 1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maxIncreasingGroups(self, usageLimits: list[int]) -> int:
    ans = 1  # the next target length
    availableLimits = 0

    for usageLimit in sorted(usageLimits):
      availableLimits += usageLimit
      # Can create groups 1, 2, ..., ans.
      if availableLimits >= ans * (ans + 1) // 2:
        ans += 1

    return ans - 1