You are given an array houses of length n, where houses[i] is the position of the i-th house on a number line. You start at position 0 and want to visit all houses in any order, but you must visit each house exactly once. The cost to move from position x to position y is |x - y|. Return the minimum total cost to visit all houses.
The minimum cost to visit all houses is achieved by visiting them in sorted order, either ascending or descending, starting from 0. This is because the sum of absolute differences between consecutive sorted positions is minimized.
classSolution {
publiclongminCost(int[] houses) {
Arrays.sort(houses);
long ans1 = Math.abs(houses[0]);
for (int i = 1; i < houses.length; i++) {
ans1 += Math.abs(houses[i]- houses[i-1]);
}
long ans2 = Math.abs(houses[houses.length-1]);
for (int i = houses.length-2; i >= 0; i--) {
ans2 += Math.abs(houses[i]- houses[i+1]);
}
return Math.min(ans1, ans2);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funminCost(houses: IntArray): Long {
houses.sort()
var ans1 = kotlin.math.abs(houses[0]).toLong()
for (i in1 until houses.size) {
ans1 += kotlin.math.abs(houses[i] - houses[i-1])
}
var ans2 = kotlin.math.abs(houses.last()).toLong()
for (i in houses.size-2 downTo 0) {
ans2 += kotlin.math.abs(houses[i] - houses[i+1])
}
return minOf(ans1, ans2)
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defminCost(self, houses: list[int]) -> int:
houses.sort()
ans1: int = abs(houses[0])
for i in range(1, len(houses)):
ans1 += abs(houses[i] - houses[i-1])
ans2: int = abs(houses[-1])
for i in range(len(houses)-2, -1, -1):
ans2 += abs(houses[i] - houses[i+1])
return min(ans1, ans2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
impl Solution {
pubfnmin_cost(houses: Vec<i32>) -> i64 {
letmut h = houses.clone();
h.sort();
letmut ans1 = (h[0]).abs() asi64;
for i in1..h.len() {
ans1 += (h[i] - h[i-1]).abs() asi64;
}
letmut ans2 = (h[h.len()-1]).abs() asi64;
for i in (0..h.len()-1).rev() {
ans2 += (h[i] - h[i+1]).abs() asi64;
}
ans1.min(ans2)
}
}