![]() |
VOOZH | about |
Given an array arr[] of even length N and an integer K denoting the range of numbers in the array i.e. the numbers in the array are in the range [1, K]. The task is to find all opposite indices pair sums possible with minimum replacements where in any replacement any number of the array can be changed to any other number in the range [1, K].
Note: Two indices i and j are said to be opposite if the distance of i from start and distance of j from the end are equal and i is in the first half of the array and j in the last half of the array.
Examples:
Input: arr[] = {1, 2, 4, 3}, K = 4
Output: 4 6
Explanation: Initially the pair sum is 1+3 = 4 and 2+4 = 6 which is not equal.
Replace 4 with 2 in one step (minimum moves) and it will give two pairs having sum 4.
Or change the 1 to 3 in one step, that will give two pairs having sum 6.
So there are two possible values of equal sum of all pairs, 4 and 6, in minimum moves.Input: arr[] = {1, 2, 4, 6, 5, 3}, K = 6
Output: 7
Explanation: The three different pair sums are 4, 7, and 10.
Change 3 to 6 and 6 to 3. and this will give all the pair sum as 7 with minimum changes.
Notice here pair sum cannot be made 4 as {4, 6} itself will require 2 .
So total changes will not be minimum.
And also pair sum cannot be made 10 as then 3 should be changed to 9 or 1 to 7.
Both the values lies outside the range [1, 6].
Approach: This problem is based on the sweeping algorithm. For every pair find the max and min value that it can take and create segments so that minimum operations can be achieved. Find the most overlapping segments and also mark the total sum in the segments. In this way, the minimum sum values that make equal pairs can be found.
Below is the implementation of the above approach.
4 6
Time Complexity: O(K)
Auxiliary Space: O(K)