File: how-many-apples-can-you-put-into-the-basket/solution.py

Date: 2026-06-06

Time: 17:01

Purpose

This file solves LeetCode 1196 — How Many Apples Can You Put into the Basket. It owns both the solution implementation and its unit tests in a single module. The problem: given a list of apple weights, return the maximum number of apples that fit in a basket with a weight capacity of 5000.

Key Components

maxNumberOfApples(weight: list[int]) -> int

A greedy function that maximizes the count of apples fitting within a 5000-unit capacity. It sorts the input ascending and greedily accumulates the lightest apples first, returning the count when adding the next apple would exceed the limit.

Contract: accepts a list of positive integer weights, returns an integer in [0, len(weight)]. Mutates the input list via weight.sort().

TestMaxNumberOfApples

Eight test cases covering: all fit, partial fit, single-element edge cases (fits / too heavy), exact capacity, none fit, uniform weights, and a large input of minimal weights.

Patterns

Greedy sort-and-accumulate: The canonical approach for "maximize count under a weight budget" problems. Sorting ascending ensures the lightest items are picked first, which is provably optimal when the objective is to maximize the number of items (not value).

Inline tests: Solution and tests colocated in one file, consistent with every other problem directory in this repo. The if _name == "main_" guard allows running tests directly.

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The testsolution.py file in this same directory, plus hundreds of other testsolution.py files across the repo reference it (the "Imported By" list in the prompt is likely an artifact of how the repo's test harness discovers modules, not direct imports of this specific function).

Flow

1. weight.sort() — in-place ascending sort, O(n log n)

2. Iterate with enumerate, accumulating a running total

3. On each iteration, add the current weight to total

4. If total > 5000, return i (the number of apples *before* this one)

5. If the loop completes without exceeding 5000, return len(weight) — all apples fit

The early return on line 17 (return i) is the key: i is zero-indexed, so it equals the count of apples added *before* the one that broke the budget.

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints (non-empty list of positive integers). No bounds checking, no exception handling. Invalid input (empty list, negative weights) would produce silently wrong results rather than errors — [] returns 0, which happens to be reasonable.

Topics to Explore

Beliefs