Divide array in two Subsets such that sum of square of sum of both subsets is maximum

Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.
Examples:Â
Input: arr[] = {1, 2, 3}Â
Output: 26Â
Explanation:Â
Sum of Subset Pairs are as followsÂ
(1)2 + (2 + 3)2 = 26Â
(2)2 + (1 + 3)2 = 20Â
(3)2 + (1 + 2)2 = 18Â
Maximum among these is 26, Therefore the required sum is 26Input: arr[] = {7, 2, 13, 4, 25, 8}Â
Output: 2845Â
Â
Approach: The task is to maximize the sum of a2 + b2 where a and b are the sum of the two subsets and a + b = C (constant), i.e., the sum of the entire array. The maximum sum can be achieved by sorting the array and dividing the first N/2 – 1 smaller elements in one subset and the rest N/2 + 1 elements in the other subset. In this way, the sum can be maximized while keeping the difference in size at most 1.
Below is the implementation of the above approach:Â
C++
// C++ implementation of the approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to return the maximum sum of the// square of the sum of two subsets of an arrayint maxSquareSubsetSum(int* A, int N){    // Initialize variables to store    // the sum of subsets    int sub1 = 0, sub2 = 0;Â
    // Sorting the array    sort(A, A + N);Â
    // Loop through the array    for (int i = 0; i < N; i++) {Â
        // Sum of the first subset        if (i < (N / 2) - 1)            sub1 += A[i];Â
        // Sum of the second subset        else            sub2 += A[i];    }Â
    // Return the maximum sum of    // the square of the sum of subsets    return sub1 * sub1 + sub2 * sub2;}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 7, 2, 13, 4, 25, 8 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â
    cout << maxSquareSubsetSum(arr, N);Â
    return 0;} |
Java
// Java implementation of the approachimport java.util.*;Â
class GFG {         // Function to return the maximum sum of the     // square of the sum of two subsets of an array     static int maxSquareSubsetSum(int []A, int N)     {         // Initialize variables to store         // the sum of subsets         int sub1 = 0, sub2 = 0;              // Sorting the array         Arrays.sort(A);              // Loop through the array         for (int i = 0; i < N; i++)         {                  // Sum of the first subset             if (i < (N / 2) - 1)                 sub1 += A[i];                  // Sum of the second subset             else                sub2 += A[i];         }              // Return the maximum sum of         // the square of the sum of subsets         return sub1 * sub1 + sub2 * sub2;     }          // Driver code     public static void main (String[] args)    {         int arr[] = { 7, 2, 13, 4, 25, 8 };         int N = arr.length;              System.out.println(maxSquareSubsetSum(arr, N));    } }Â
// This code is contributed by AnkitRai01 |
Python3
# Python3 implementation of the approach Â
# Function to return the maximum sum of the # square of the sum of two subsets of an array def maxSquareSubsetSum(A, N) :Â
    # Initialize variables to store     # the sum of subsets     sub1 = 0; sub2 = 0;         # Sorting the array    A.sort();Â
    # Loop through the array     for i in range(N) :Â
        # Sum of the first subset         if (i < (N // 2) - 1) :            sub1 += A[i]; Â
        # Sum of the second subset         else :            sub2 += A[i]; Â
    # Return the maximum sum of     # the square of the sum of subsets     return sub1 * sub1 + sub2 * sub2; Â
# Driver code if __name__ == "__main__" : Â
    arr = [ 7, 2, 13, 4, 25, 8 ];     N = len(arr); Â
    print(maxSquareSubsetSum(arr, N)); Â
# This code is contributed by AnkitRai01 |
C#
// C# implementation of the approachusing System;Â
class GFG {         // Function to return the maximum sum of the     // square of the sum of two subsets of an array     static int maxSquareSubsetSum(int []A, int N)     {         // Initialize variables to store         // the sum of subsets         int sub1 = 0, sub2 = 0;              // Sorting the array         Array.Sort(A);              // Loop through the array         for (int i = 0; i < N; i++)         {                  // Sum of the first subset             if (i < (N / 2) - 1)                 sub1 += A[i];                  // Sum of the second subset             else                sub2 += A[i];         }              // Return the maximum sum of         // the square of the sum of subsets         return sub1 * sub1 + sub2 * sub2;     }          // Driver code     public static void Main()    {         int []arr = { 7, 2, 13, 4, 25, 8 };         int N = arr.Length;              Console.WriteLine(maxSquareSubsetSum(arr, N));    } }Â
// This code is contributed by AnkitRai01 |
Javascript
<script>// javascript implementation of the approach// Creating the bblSort function function bblSort(arr){       for(var i = 0; i < arr.length; i++){         // Last i elements are already in place    for(var j = 0; j < ( arr.length - i -1 ); j++){             // Checking if the item at present iteration      // is greater than the next iteration     if(arr[j] > arr[j+1]){                 // If the condition is true then swap them       var temp = arr[j]       arr[j] = arr[j + 1]       arr[j+1] = temp     }   } } // return the sorted array return arr;}    // Function to return the maximum sum of the    // square of the sum of two subsets of an array    function maxSquareSubsetSum(A , N) {        // Initialize variables to store        // the sum of subsets        var sub1 = 0, sub2 = 0;Â
        // Sorting the array        A = bblSort(A);Â
        // Loop through the array        for (i = 0; i < N; i++) {Â
            // Sum of the first subset            if (i < (N / 2) - 1)                sub1 += A[i];Â
            // Sum of the second subset            else                sub2 += A[i];        }Â
        // Return the maximum sum of        // the square of the sum of subsets        return sub1 * sub1 + sub2 * sub2;    }Â
    // Driver code             var arr = [ 7, 2, 13, 4, 25, 8 ];        var N = arr.length;Â
        document.write(maxSquareSubsetSum(arr, N));Â
// This code is contributed by todaysgaurav</script> |
2845
Â
Time Complexity: O(N*log(N))
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



