#K91867. Minimizing Cost by Reversing a Subarray
Minimizing Cost by Reversing a Subarray
Minimizing Cost by Reversing a Subarray
Alice has a list of integers and she wants to minimize the cost of the list after performing a specific operation. The cost of the list is defined as the sum of the absolute differences between consecutive elements. Alice can choose to reverse any contiguous subarray in the list exactly once. Your task is to compute the minimum possible cost after performing this operation.
Formally, given an array \(L = [a_0, a_1, \dots, a_{n-1}]\), its cost is defined as:
$$\text{Cost}(L) = \sum_{i=1}^{n-1} |a_i - a_{i-1}|. $$You are allowed to choose one subarray \(L[i\ldots j]\) (with \(0 \le i < j < n\)) and reverse its elements, or perform no reversal if it does not reduce the cost. Find the minimum cost achievable.
inputFormat
The input is read from stdin
and consists of two lines:
- The first line contains an integer n, representing the number of elements in the array.
- The second line contains n space-separated integers, which are the elements of the array.
outputFormat
Output a single integer to stdout
, which is the minimum possible cost of the array after performing at most one reversal operation over a contiguous subarray.
4
1 3 4 2
4
</p>