import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.*
import kotlin.math.abs
import kotlin.math.min
fun main() = with(BufferedReader(InputStreamReader(System.`in`))) {
val n = readLine().toInt()
val st = StringTokenizer(readLine())
val rankings = MutableList(n) {
st.nextToken().toInt()
}
print(getMinDiffSum(rankings))
}
fun getMinDiffSum(rankings: MutableList<Int>): Int {
var sumOfDiff = 0 // 정답
while (rankings.size > 1) {
var maxRankIndex = 0
// 랭킹값이 큰 선수부터 제거
for (i in 0 until rankings.size) {
if (rankings[i] == rankings.size) {
maxRankIndex = i
break
}
}
// 차이가 작은 선수들을 붙인다
sumOfDiff += when {
maxRankIndex == 0 -> abs(rankings[maxRankIndex] - rankings[maxRankIndex + 1])
maxRankIndex == rankings.lastIndex -> abs(rankings[maxRankIndex] - rankings[maxRankIndex - 1])
else -> min(
abs(rankings[maxRankIndex] - rankings[maxRankIndex + 1]),
abs(rankings[maxRankIndex] - rankings[maxRankIndex - 1])
)
}
rankings.removeAt(maxRankIndex)
}
return sumOfDiff
}