How Many Apples Can You Put into the Basket - Problem

You have some apples and a basket that can carry up to 5000 units of weight.

Given an integer 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.

Input & Output

Example 1 — Basic Case
$ Input: weight = [100,200,150,500]
Output: 4
💡 Note: All apples can fit: 100 + 200 + 150 + 500 = 950 ≤ 5000, so we can take all 4 apples
Example 2 — Weight Limit Exceeded
$ Input: weight = [900,950,800,1000,700,800]
Output: 5
💡 Note: After sorting: [700,800,800,900,950,1000]. We can take 700+800+800+900+950=4150 ≤ 5000, but adding 1000 would exceed limit
Example 3 — Single Heavy Apple
$ Input: weight = [5001]
Output: 0
💡 Note: The single apple weighs 5001 > 5000, so we cannot take any apples

Constraints

  • 1 ≤ weight.length ≤ 103
  • 1 ≤ weight[i] ≤ 104

Visualization

Tap to expand
How Many Apples Can You Put into the Basket? INPUT weight[] array 100 [0] 200 [1] 150 [2] 500 [3] Basket Capacity 5000 units max 100 200 150 500 ALGORITHM STEPS 1 Sort Array Ascending order (lightest first) 100 150 200 500 2 Initialize Variables count = 0, sum = 0 3 Greedy Selection Add apples while sum <= 5000 Apple Sum Count OK? 100 100 1 OK 150 250 2 OK 200 450 3 OK 500 950 4 OK 4 Return Count All apples fit! Return 4 FINAL RESULT 100 150 200 500 Total Weight: 100+150+200+500 = 950 units (under 5000) Output: 4 All 4 apples fit in basket! Key Insight: Greedy approach works here! By sorting apples by weight and picking the lightest ones first, we maximize the number of apples that fit in the basket. Time Complexity: O(n log n) for sorting. TutorialsPoint - How Many Apples Can You Put into the Basket | Greedy - Sort and Pick Lightest
Asked in
Amazon 35 Google 28 Microsoft 22 Apple 18
32.4K Views
Medium Frequency
~12 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen