KatInterview

Balance Integer Values to Minimize Spread

Math & Bit ManipulationAuto-graded · 24 test cases
MediumAuto-gradedMath & Bit Manipulationmathgreedydivision

Last updated

Tests understanding of integer division, remainder distribution, and handling negative numbers in a fairness optimization problem.

You are given a list of integers representing values that can be positive, negative, or zero. Your task is to balance these values so that the spread between the largest and smallest result is minimized, while keeping the total sum unchanged.

The optimal balance distributes the total as evenly as possible: some values will be ⌊total/n⌋ and others will be ⌊total/n⌋ + 1, where n is the number of values.

Return a list of the balanced values in non-decreasing order.

Constraints

  • 0 ≤ len(values) ≤ 10⁵
  • -10⁹ ≤ values[i] ≤ 10⁹
  • The sum of all values fits in a 64-bit signed integer
  • The output must preserve the total sum exactly
  • Return an empty list if the input is empty

Examples

Example 1

Input: balance_values([10, 0, 0])

Output: [3, 3, 4]

Example 2

Input: balance_values([1, 2, 3, 4])

Output: [2, 2, 3, 3]

Example 3

Input: balance_values([5, -5, 10])

Output: [3, 3, 4]

Example 4

Input: balance_values([7, 7, 7])

Output: [7, 7, 7]

Hints

Hint 1

The total sum must remain constant after redistribution. How many values can you have at each level?

Hint 2

If the total doesn't divide evenly by n, exactly (total mod n) values must be one unit higher than the rest.

Hint 3

Python's floor division handles negative numbers correctly: -7 // 3 = -3, with remainder 2. The remainder is always non-negative.