Lv.1mathprefix-sumsorting
Total Pairwise Distance
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
houses gives the positions of n houses on a straight road (unsorted, possibly repeated). Return the sum of
|houses[i] - houses[j]| over all pairs i < j.
Examples
| houses | result |
|---|---|
[1, 3, 6] | 10 |
[5, 5, 5] | 0 |
[8, 0, 2, 2] | 24 |
Example 1 — 2 + 5 + 3 = 10.
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 may not fit in 32 bits; use a 64-bit integer (
long).
Expected complexity
- Time
- O(N log N)
- Space
- O(N)
Examples
| houses | Expected |
|---|---|
[1,3,6] | 10 |
[5,5,5] | 0 |
[8,0,2,2] | 24 |
Hint
Hint
Sort the positions first. In sorted order, house j contributes against all earlier
houses; keep a running prefix sum and use 64-bit integers. Adding every pair's distance is and exceeds the time limit.
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 | 1186 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 | 10 | verdict only |
| performance | 60 | 4 | verdict only |