Hay Bales

Interview

Time limit1sMemory limit128 MB

Summary
Given N piles of hay with possibly unequal heights, find the minimum number of bales to move so all piles have equal height.
Level

Easy3 of 10

Topics
Array, Math, Greedy
Solved
No attempts yet

Problem

The cows are at it again! Farmer John has carefully arranged NN (1≤N≤10,0001 \le N \le 10{,}000) piles of hay bales, each of the same height. When he isn't looking, however, the cows move some of the hay bales between piles, so their heights are no longer necessarily the same. Given the new heights of all the piles, help Farmer John determine the minimum number of hay bales he needs to move in order to restore all the piles to their original, equal heights.

Input

  • Line 1: The number of piles, NN (1≤N≤10,0001 \le N \le 10{,}000).
  • Lines 2 to N+1N+1: Each line contains the number of hay bales in a single pile (an integer between 11 and 10,00010{,}000, inclusive).

Output

  • Line 1: An integer giving the minimum number of hay bales that need to be moved to make all piles have equal height.

Hint

Input Details

There are 4 piles, of heights 2, 10, 7, and 1.

Output Details

By moving 7 hay bales (3 from pile 2 to pile 1, 2 from pile 2 to pile 4, 2 from pile 3 to pile 4), all piles can be made to have height 5.

Examples1

  1. Example 1

    Input
    4
    2
    10
    7
    1
    
    Expected output
    7