VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-square-sum-of-given-arrays-by-swapping-elements-at-same-indices/

⇱ Minimize square sum of given Arrays by swapping elements at same indices - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize square sum of given Arrays by swapping elements at same indices

Last Updated : 23 Jul, 2025

 Given two arrays arrA[] and arrB[] containing N integers each. Perform the following operation any number of times (possibly zero):

  • Select any index i (0 <= i <= N-1) and
  • Swap arrA[i] and arrB[i].

The task is to find the minimum sum of the square of array sums i.e. if Sa and Sb are the array sum of arrA[] and arrB[] after swapping, then find the minimum possible value of (Sa)2 + (Sb)2.

Examples:

Input : N = 4, arrA[ ] = { 3, 6, 6, 6 }, arrB[ ] = { 2, 7, 4, 1 }
Output: 613
Explanation : 
If we perform the operation for i = 0 and i = 2, we get the resultant arrays as arrA[] = { 2, 6, 4, 6 } and arrB[] = { 3, 7, 6, 1 }. 
Thus Sa = 18 and Sb = 17. 
So, sum of their squares is (18)2 + (17)2 = 613, which is the minimum possible.

Input : N = 4, arrA[ ] = { 6, 7, 2, 4 }, arrB[ ] = { 2, 5, 3, 5 }
Output: 578

Naive Approach: The naive approach is to check all possible cases. For each index: 

  • Either swap those elements of that index or not.
    • Calculate the sum of the arrays.
    • Find the value of sum of square of array sums.
  • The minimum of the values is the answer.

Time Complexity: O(2N * N)
Auxiliary Space: O(1) 

Efficient Approach: The efficient approach is based on the following idea:

Use memoization to store the already calculated result up to an index and some array sum which will prevent repeated calculation and reduce the overall time.

Follow the steps mentioned below to implement the above idea:

  • Create a dp[] array to store the calculated sum of squares of array sum up to some index i and array sums Sa and Sb.
  • For each index there are two choices: either swap the elements or not.
  • Perform this swap operation recursively and:
    • If for any index the value is already calculated then return that value.
    • Otherwise, calculate the sum and store the minimum value possible for that index.
  • Return the minimum sum among all as the answer.

Below is the implementation of the above approach. 

 
 


Output
578


 

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


 

Comment
Article Tags: