VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-sum-of-an-array-by-swapping-a-subarray-with-another-array/

⇱ Minimize sum of an Array by swapping a Subarray with another Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize sum of an Array by swapping a Subarray with another Array

Last Updated : 23 Jul, 2025

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:

  • Create two difference arrays (say t[] and s[]) to store the values of (A[i]-B[i]) and (B[i]-A[i]) respectively.
  • Calculate the sum of the arrays.
  • Now find the maximum subarray sums from t[] and s[] using Kadane's algorithm.
  • Subtract these values from the respective array sum and the minimum between them is the required answer.

Below is the implementation of the above approach.


Output
90

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment
Article Tags: