Lv.1mathsorting
Post Office Location
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Acceptance
- 100.0%
- Solvers
- 1
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
| houses | result |
|---|---|
[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
-
houses.length,houses[i] - The answer can exceed 32 bits.
Expected complexity
- Time
- O(N log N)
- Space
- O(1)
Examples
| houses | Expected |
|---|---|
[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 .
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1302 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 7 | verdict only |
| performance | 60 | 4 | verdict only |