Ctrl K

Level the Jars

Medium
A shelf holds jars of sweets: jar i contains jars[i] sweets. You want every non-empty jar to hold the same number of sweets. You may only take sweets out (from any jar, as many as you like, including all of them); you cannot move them between jars or add new ones. Return the smallest number of sweets you have to take out.
Example 1
jars=[3, 8, 2, 7] → 6

Keep 7 sweets per jar: take 1 from the jar of 8 and empty the jars of 3 and 2. That is 1 + 3 + 2 = 6 removed.

Example 2
jars=[5, 5, 1] → 1

Emptying the jar with a single sweet is enough.

Example 3
jars=[4, 6, 6, 6] → 4

Emptying the jar of 4 (taking out 4) is cheaper than cutting every 6 down to 4 (taking out 2 + 2 + 2 = 6).

Constraints
  • 1 ≤ len(jars) ≤ 10⁵
  • 1 ≤ jars[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFlowerbed Beauty on a Budget HardStudios for Recording Sessions MediumArrange for the Busiest Ranges MediumEven Out With Increments MediumRug Over Painted Stretches Medium
loading Python…
Input
jars=[3, 8, 2, 7]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 109 tests on the server, hidden ones included.