# Program to find number of operations needed to make pairs from first and last side are with same sum in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers called nums. The length of this list is even. Now consider an operation where we select any number in nums and update it with a value in range [1 and maximum of nums]. We have to find the minimum number of such operations required such that, for every i, nums[i] + nums[n-1-i] equals to the same number.

So, if the input is like nums = [8,6,2,5,9,2], then the output will be 2, because if we change first 2 at nums[2] to 5, and 9 at nums[4] to 4, then the elements will be [8,6,5,5,4,2], then the nums[i] + nums[n-1-i] for each i will be (8+2) = (6+4) = (5+5) = 10.

To solve this, we will follow these steps −

• N := size of nums
• mx := maximum of nums
• events := a new list
• idx := 0
• while idx < floor of N / 2, do
• a := nums[idx]
• b := nums[N - idx - 1]
• insert a pair (minimum of (a + 1), (b + 1), 1) at the end of events
• insert a pair (a + b, 1) at the end of events
• insert a pair (a + b + 1, -1) at the end of events
• insert a pair (maximum of (a + mx) and (b + mx + 1), -1) at the end of events
• idx := idx + 1
• sort the list events
• current := 0
• mx_same := 0
• for each pair (event, delta) in events, do
• current := current + delta
• mx_same := maximum of current and mx_same
• return N - mx_same

## Example

Let us see the following implementation to get better understanding −

def solve(nums):
N = len(nums)
mx = max(nums)
events = []

idx = 0
while idx < N // 2:
a = nums[idx]
b = nums[N - idx - 1]

events.append((min(a + 1, b + 1), 1))
events.append((a + b, 1))
events.append((a + b + 1, -1))
events.append((max(a + mx, b + mx) + 1, -1))

idx += 1

events.sort()
current = 0
mx_same = 0

for event, delta in events:
current += delta
mx_same = max(current, mx_same)

return N - mx_same

nums = [8,6,2,5,9,2]
print(solve(nums))

## Input

[6, 8, 5, 2, 3]

## Output

2
Updated on 18-Oct-2021 12:49:34