Skip to content

2279. Maximum Bags With Full Capacity of Rocks 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int maximumBags(vector<int>& capacity, vector<int>& rocks,
                  int additionalRocks) {
    const int n = capacity.size();
    vector<int> diff(n);

    for (int i = 0; i < n; ++i)
      diff[i] = capacity[i] - rocks[i];

    ranges::sort(diff);

    for (int i = 0; i < n; ++i) {
      if (diff[i] > additionalRocks)
        return i;
      additionalRocks -= diff[i];
    }

    return n;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int maximumBags(int[] capacity, int[] rocks, int additionalRocks) {
    final int n = capacity.length;
    int[] diff = new int[n];

    for (int i = 0; i < n; ++i)
      diff[i] = capacity[i] - rocks[i];

    Arrays.sort(diff);

    for (int i = 0; i < n; ++i) {
      if (diff[i] > additionalRocks)
        return i;
      additionalRocks -= diff[i];
    }

    return n;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def maximumBags(
      self,
      capacity: list[int],
      rocks: list[int],
      additionalRocks: int,
  ) -> int:
    for i, d in enumerate(sorted([c - r for c, r in zip(capacity, rocks)])):
      if d > additionalRocks:
        return i
      additionalRocks -= d
    return len(capacity)