According to the problem description, we need to find the maximum value of the array \(\sum_{i=0}^{n-2} |a_i - a_{i+1}|\) when reversing a subarray once.
Next, we discuss the following cases:
Do not reverse the subarray.
Reverse the subarray, and the subarray "includes" the first element.
Reverse the subarray, and the subarray "includes" the last element.
Reverse the subarray, and the subarray "does not include" the first and last elements.
Let \(s\) be the array value when the subarray is not reversed, then \(s = \sum_{i=0}^{n-2} |a_i - a_{i+1}|\). We can initialize the answer \(ans\) to \(s\).
If we reverse the subarray and the subarray includes the first element, we can enumerate the last element \(a_i\) of the reversed subarray, where \(0 \leq i < n-1\). In this case, \(ans = \max(ans, s + |a_0 - a_{i+1}| - |a_i - a_{i+1}|)\).
Similarly, if we reverse the subarray and the subarray includes the last element, we can enumerate the first element \(a_{i+1}\) of the reversed subarray, where \(0 \leq i < n-1\). In this case, \(ans = \max(ans, s + |a_{n-1} - a_i| - |a_i - a_{i+1}|)\).
If we reverse the subarray and the subarray does not include the first and last elements, we consider any two adjacent elements in the array as a point pair \((x, y)\). Let the first element of the reversed subarray be \(y_1\), and its left adjacent element be \(x_1\); let the last element of the reversed subarray be \(x_2\), and its right adjacent element be \(y_2\).
At this time, compared to not reversing the subarray, the change in the array value is \(|x_1 - x_2| + |y_1 - y_2| - |x_1 - y_1| - |x_2 - y_2|\), where the first two terms can be expressed as:
Therefore, we only need to find the maximum value \(mx\) of \(k_1 \times x + k_2 \times y\), where \(k_1, k_2 \in \{-1, 1\}\), and the corresponding minimum value \(mi\) of \(|x - y|\). Then the maximum change in the array value is \(mx - mi\). The answer is \(ans = \max(ans, s + \max(0, mx - mi))\).
In the code implementation, we define an array of length 5, \(dirs=[1, -1, -1, 1, 1]\). Each time we take two adjacent elements of the array as the values of \(k_1\) and \(k_2\), which can cover all cases of \(k_1, k_2 \in \{-1, 1\}\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(nums\). The space complexity is \(O(1)\).