We can check if the array is already balanced by storing 4 arrays, prefix minimum, prefix maximum, suffix minimum and suffix maximum. We will go to all indices and check if equals using our pre-computed arrays. If the array is already Balanced, the answer is 0.
Otherwise, we can always do 1 operation to make the array Balanced. Let us pick , so we get and . We can select and set the value of to and then will equal .
Author’s solution: https://ideone.com/UqT1Cw