LeetCode 1196: How Many Apples Can You Put into the Basket Solution

Master LeetCode problem 1196 (How Many Apples Can You Put into the Basket), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1196. How Many Apples Can You Put into the Basket

Problem Explanation

Explanation:

To solve this problem, we need to determine the maximum number of apples that can be put into a basket given the weight capacity of the basket. We are given an array where each element represents the weight of an apple. The basket can only carry a maximum weight of maxWeight and we can only put apples into the basket that weigh less than or equal to the maxWeight.

We can use a greedy approach to solve this problem. We will sort the array of apple weights in non-decreasing order. Then, we will start putting apples into the basket one by one until we reach the maximum weight capacity. If adding the next apple exceeds the maximum weight, we stop and return the count of apples added. :

Solution Code

import java.util.Arrays;

class Solution {
    public int maxNumberOfApples(int[] arr, int maxWeight) {
        Arrays.sort(arr);
        int count = 0;
        int totalWeight = 0;
        for (int weight : arr) {
            if (totalWeight + weight <= maxWeight) {
                count++;
                totalWeight += weight;
            } else {
                break;
            }
        }
        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1196 (How Many Apples Can You Put into the Basket)?

This page provides optimized solutions for LeetCode problem 1196 (How Many Apples Can You Put into the Basket) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1196 (How Many Apples Can You Put into the Basket)?

The time complexity for LeetCode 1196 (How Many Apples Can You Put into the Basket) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1196 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1196 in Java, C++, or Python.

Back to LeetCode Solutions