2
def maxValueAfterReverse(self, nums):7
# basic idea without fancy stuff8
# 1. https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/discuss/489929/O(n)-time-O(1)-space.-In-depth-Explanation9
# 2. https://code.dennyzhang.com/reverse-subarray-to-maximize-array-value11
# This can be done in three steps each step taking O(N) time15
# Step 1: Assume that no subarray is reversed and so the sum would just accumulate over all the abs differences16
for index in range(1, n):17
res += abs(nums[index] - nums[index - 1])19
# Step 2: Reversing the left or the right half so basically this idea stems from prefix array type question where in which we have the sum upto ith index but then to get at a specific index we substract extra sum, following from that idea. Or refer to the reference 122
for index in range(n):24
# reversing from 0th index to current28
abs(nums[index + 1] - nums[0]) - abs(nums[index + 1] - nums[index]),29
) # diff between 0 and curr - diff curr and curr + 131
# reversing from current to last index n - 135
abs(nums[index - 1] - nums[n - 1])36
- abs(nums[index - 1] - nums[index]),39
# Step 3: We still need to check the middle reverse part, we can do this using the min max trick40
low_number, high_number = float("inf"), float("-inf")42
for index in range(n - 1):45
low_number, max(nums[index], nums[index + 1])46
) # min of low and the max of the current and next number47
high_number = max(high_number, min(nums[index], nums[index + 1]))50
diff, 2 * (high_number - low_number)51
) # This is explained in ref 1