File: minimum-cost-of-buying-candies-with-discount/solution.py

Date: 2026-06-06

Time: 17:54

Purpose

This file solves LeetCode 2144: Minimum Cost of Buying Candies With Discount. The problem: you buy candies and for every two you pay for, you get one free (the free one must cost no more than the minimum of the two you paid for). The goal is to minimize total spend.

Key Components

Solution.minimumCost(cost: List[int]) -> int — The core solver. Takes a list of candy prices, returns the minimum total cost after optimally applying the "buy 2, get 1 free" discount.

maxdifference — A class-level alias pointing to minimumCost. The comment says "Task requires this alias," which suggests the test harness or a shared test runner expects this name. This is likely a copy-paste artifact from another solution's scaffolding — maxdifference has no semantic relationship to this problem.

Patterns

Greedy via sort-then-skip. The algorithm sorts descending and skips every third element (index % 3 == 2). This is the canonical greedy approach: by paying for the two most expensive candies first, you maximize the value of the free candy. The pattern of sort + enumerate + modular index filter is a compact idiom for "process in groups of K, skipping some."

In-place mutation. cost.sort(reverse=True) mutates the caller's list. This is a minor contract concern — the caller's data is reordered after the call.

Dependencies

Imports: Only typing.List — no external libraries.

Imported by: The test file minimum-cost-of-buying-candies-with-discount/test_solution.py. The massive "Imported By" list in the prompt is noise — those are unrelated test files that happen to import a Solution class from their own sibling solution.py, not this one.

Flow

1. Sort cost in descending order (highest price first).

2. Enumerate the sorted list. For each candy at index i:

3. Sum and return the included costs.

Concretely, for cost = [1, 2, 3, 4, 5, 6]:

Invariants

Error Handling

None. The function assumes valid input per LeetCode constraints (1 <= cost.length <= 100, 1 <= cost[i] <= 100). Empty lists would return 0 (correct but not explicitly guarded).

Topics to Explore

Beliefs