![]() |
VOOZH | about |
Given two arrays arrA[] and arrB[] containing N integers each. Perform the following operation any number of times (possibly zero):
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:
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:
Below is the implementation of the above approach.
578
Time Complexity: O(N3)
Auxiliary Space: O(N3)