Решение
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import kotlin.math.min
fun main() {
val reader = BufferedReader(InputStreamReader(System.`in`))
val writer = BufferedWriter(OutputStreamWriter(System.out))
val n = reader.readLine().toInt()
val coords = reader.readLine().split(" ").map { it.toInt() }.sorted()
if (n == 2) {
writer.write((coords[1] - coords[0]).toString())
} else {
// dp[i] stores the minimum cost for the first i+1 nails (indices 0 to i)
val dp = IntArray(n)
// Base case: dp[0] is not used as N >= 2
// Base case: dp[1] covers nails 0, 1. Must connect (0,1).
dp[1] = coords[1] - coords[0]
// Base case: dp[2] covers nails 0, 1, 2. Must connect (0,1) and (1,2).
// Cost = (coords[1] - coords[0]) + (coords[2] - coords[1]) = coords[2] - coords[0]
if (n > 2) {
dp[2] = dp[1] + (coords[2] - coords[1])
}
// Recurrence for i >= 3 (covering nails 0 to i)
// Nail i must be connected to nail i-1 (cost: coords[i] - coords[i-1])
// We need to ensure nails 0 to i-1 are covered.
// Option 1: Build upon dp[i-1] (covers 0..i-1). Add connection (i-1, i).
// Option 2: Build upon dp[i-2] (covers 0..i-2). Add connection (i-1, i).
// Choose the minimum of the previous states.
for (i in 3 until n) {
val costI = coords[i] - coords[i - 1]
dp[i] = min(dp[i - 1], dp[i - 2]) + costI
}
// The final answer is the minimum cost to cover all N nails (indices 0 to n-1)
writer.write(dp[n - 1].toString())
}
writer.flush()
reader.close()
writer.close()
}