Skip to content

1196. How Many Apples Can You Put into the Basket 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxNumberOfApples(vector<int>& weight) {
    int sum = 0;

    ranges::sort(weight);

    for (int i = 0; i < weight.size(); ++i) {
      sum += weight[i];
      if (sum > 5000)
        return i;
    }

    return weight.size();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maxNumberOfApples(int[] weight) {
    int sum = 0;

    Arrays.sort(weight);

    for (int i = 0; i < weight.length; ++i) {
      sum += weight[i];
      if (sum > 5000)
        return i;
    }

    return weight.length;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def maxNumberOfApples(self, weight: list[int]) -> int:
    summ = 0

    for i, w in enumerate(sorted(weight)):
      summ += w
      if summ > 5000:
        return i

    return len(weight)