![]() |
VOOZH | about |
Given two arrays A[] and B[] each of size N, the task is to minimize the sum of an array by swapping a subarray.
Examples:
Input: A[] = {10, 30, 10, 60, 20}, B[] = {40, 10, 40, 30, 10}
Output: 90
Explanation: Swap the subarray {30, 10} with {60, 20}.
The sum of array A[] = 10+30+10+30+10 = 90.
The sum of array B[] = 40+10+40+60+20 = 170.
The minimum sum = 90.
It is the minimum possible sum an array can achieve.Input: A[] = {10, 20, 30}, B[] = {1, 2, 3}
Output: 6
Approach: To problem can be solved based on the following idea:
To minimize the sum of an array, we should swap such a subarray where the difference between the subarray sum is maximum i.e. for array A[] the value of (subarray of A[] - subarray of B[]) is maximum and the same for array B[].
The minimum between these two values will be the answer.To implement this we can create two difference arrays and calculate the largest subarray sum from those difference arrays and subtract them from array sum.
Follow the steps mentioned below to implement the above idea:
Below is the implementation of the above approach.
90
Time Complexity: O(N)
Auxiliary Space: O(N)