All problems
0894MediumArrayGreedySortingEnumerationPrefix Sum

Levelling the Seed Sacks

Tracked in this browser only
Write code

Trains the technique from

LeetCode 2171Removing Minimum Number of Magic Beans

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A row of sacks holds seeds, beans[i] in sack i. Removing a seed takes it out of its sack for good.

The row is level when every sack that still holds any seeds holds the same number as every other such sack. A sack emptied completely does not count.

Return the fewest seeds that must be removed to leave the row level.

Examples

Example 1

Input
beans = [13, 4, 27, 4, 19]
Output
28

Levelling at 13 empties the two sacks of 4 and cuts 27 and 19 back, removing 4 plus 4 plus 14 plus 6, which is 28. Levelling at 19 removes 4, 4, 13 and 8, which is 29, and levelling at 4 removes 45, so 13 is the level to pick.

Example 2

Input
beans = [1, 100000]
Output
1

Emptying the sack of 1 leaves the big sack untouched, which costs a single seed. Cutting the big sack down to 1 would cost far more.

Example 3

Input
beans = [8, 8, 8, 8]
Output
0

The row is already level.

Constraints

  • 1 <= beans.length <= 10^5
  • 1 <= beans[i] <= 10^5

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def minimum_removal(beans: list[int]) -> int:
Java
public long minimumRemoval(int[] beans)
September 7
Apply