Show problems as
Classic problem #2144EasyArrayGreedySorting

Minimum Cost of Buying Candies With Discount

Real-world version: Least Paid at the Clamp Stall
Tracked in this browser only
Read Minimum Cost of Buying Candies With Discount on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A hardware stall prices every clamp on its table separately; price[i] is the price of the i-th clamp. You want to take all of them home, and the stall runs this offer.

Split the clamps into groups however you like, so that every clamp belongs to exactly one group. In a group of exactly three clamps, the cheapest clamp of that group is free and you pay for the other two. In a group of any other size, you pay for every clamp in it.

Return the smallest total you can pay for all of the clamps.

Examples

Example 1

Input
price = [8, 3, 6, 1]
Output
15

Put the clamps priced 8, 6 and 3 in one group: 3 is the cheapest of that group, so it is free and you pay 8 and 6. The clamp priced 1 sits in a group of its own and is paid for, giving 8 + 6 + 1 = 15.

Example 2

Input
price = [40, 40, 40, 40]
Output
120

Group three of the clamps, taking one of them free and paying for the other two, and leave the fourth in a group of its own, giving 40 + 40 + 40 = 120.

Example 3

Input
price = [9]
Output
9

One clamp cannot form a group of three, so it is paid for.

Constraints

  • 1 <= price.length <= 100
  • 1 <= price[i] <= 100

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def least_paid(price: list[int]) -> int:
Java
public int leastPaid(int[] price)