How Many Apples Can You Put into the Basket

easy greedy sorting array

Problem

You have a basket that can carry apples with total weight not exceeding 5000 units. Given an array weight where weight[i] is the weight of the i-th apple, return the maximum number of apples you can put in the basket.

Inputweight = [100, 200, 150, 1000]
Output4
All 4 apples sum to 1450 ≤ 5000, so every apple fits.

def max_number_of_apples(weight):
    weight.sort()
    total = 0
    count = 0
    for w in weight:
        if total + w > 5000:
            break
        total += w
        count += 1
    return count
function maxNumberOfApples(weight) {
  weight.sort((a, b) => a - b);
  let total = 0, count = 0;
  for (const w of weight) {
    if (total + w > 5000) break;
    total += w;
    count++;
  }
  return count;
}
class Solution {
    public int maxNumberOfApples(int[] weight) {
        Arrays.sort(weight);
        int total = 0, count = 0;
        for (int w : weight) {
            if (total + w > 5000) break;
            total += w;
            count++;
        }
        return count;
    }
}
int maxNumberOfApples(vector<int>& weight) {
    sort(weight.begin(), weight.end());
    int total = 0, count = 0;
    for (int w : weight) {
        if (total + w > 5000) break;
        total += w;
        count++;
    }
    return count;
}
Time: O(n log n) Space: O(1)