n = gets.not_nil!.to_i a = gets.not_nil!.split.map(&.to_i64).sort dp = [10_i64**18]*(n+1) dp[0] = 0 n.times do |i| dp[i+2] = [dp[i+2],dp[i]+a[i+1]-a[i]].min if i+2<=n dp[i+3] = [dp[i+3],dp[i]+a[i+2]-a[i]].min if i+3<=n end puts dp[n]