To maximize the number of apples in the basket without exceeding the weight limit, always pick the lightest apples first. This way, you can fit as many as possible before reaching the 5000 weight cap.
classSolution {
public:int maxNumberOfApples(vector<int>& weight) {
sort(weight.begin(), weight.end());
int sum =0, ans =0;
for (int w : weight) {
sum += w;
if (sum >5000) break;
++ans;
}
return ans;
}
};
classSolution {
publicintmaxNumberOfApples(int[] weight) {
Arrays.sort(weight);
int sum = 0, ans = 0;
for (int w : weight) {
sum += w;
if (sum > 5000) break;
ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaxNumberOfApples(weight: IntArray): Int {
weight.sort()
var sum = 0var ans = 0for (w in weight) {
sum += w
if (sum > 5000) break ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaxNumberOfApples(self, weight: list[int]) -> int:
weight.sort()
s =0 ans =0for w in weight:
s += w
if s >5000:
break ans +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnmax_number_of_apples(weight: Vec<i32>) -> i32 {
letmut w = weight;
w.sort();
letmut s =0;
letmut ans =0;
for x in w {
s += x;
if s >5000 { break; }
ans +=1;
}
ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
maxNumberOfApples(weight: number[]):number {
weight.sort((a, b) =>a-b);
lets=0, ans=0;
for (constwofweight) {
s+=w;
if (s>5000) break;
ans++;
}
returnans;
}
}