Funcia
Lv.1mathsorting

Post Office Location

Memory limit
256 MB
Correctness time limit
10000 ms
Acceptance
100.0%
Solvers
1
0

Houses stand on a line at coordinates houses[i] (duplicates allowed). Build a post office at one integer coordinate so that the sum of distances from all houses is minimal, and return that sum.

Examples

housesresult
[1, 2, 9]8
[5, -3, 5, 10]13
[7]0

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(houses: int[]) → long

Constraints

  • 1≤1 \le houses.length ≤200,000\le 200{,}000, −109≤-10^9 \le houses[i] ≤109\le 10^9
  • The answer can exceed 32 bits.

Expected complexity

Time
O(N log N)
Space
O(1)

Examples

housesExpected
[1,2,9]8
[5,-3,5,10]13
[7]0

Hint

Hint

The optimum is the median: moving right by 1 changes the sum by (#left − #right). Sort (or select) and sum distances to houses[n / 2] in 64 bits. Trying every house as the location is O(N2)O(N^2).

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)200 msestimated
C++ (GCC, gnu++23)200 msderived
Python 3.131000 msderived
Java 251302 msderived
Kotlin 2.4 (JVM)1400 msestimated
C# 14 (.NET 10)1400 msestimated

Test groups

GroupWeightTestsVisibility
sample03inputs and outputs
correctness407verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.