# Maximize the difference between two subsets of a set with negatives in C

CServer Side ProgrammingProgramming

We are given with an array of positive and negative integers. The task is to find the maximum difference between positive and negative subsets of elements present in the array. As we have subsets of positive and negative numbers. Then the difference (sum of positives) - (sum of negatives) will always be maximum. This is because subtracting negatives will add them. Converting all negatives into positive and adding all the elements of the array will produce the desired result. Let us see examples for understanding −

Input − Arr[] = { -2, 0, -3, 8, 10, 12, -4 }

Output − Maximized difference between two subsets − 39

Explanation − positive integers subset {0, 8,10,12} sum is 30

Negative integers subset { -2, -3, -4 } sum is -9

Maximum difference will be 30 - (-9) = 39

Input − Arr[] = { -5, -15, -3, -2, 10, 20, 15 }

Output − Maximized difference between two subsets − 70

Explanation − positive integers subset { 10, 20, 15 } sum is 45

Negative integers subset { -5, -15, -3, -2 } sum is -25

Maximum difference will be 45 - (-25) = 70

## Approach used in the below program is as follows

• We take an integer array having positive and negative integers as Arr[]

• The function subsetDifference( int arr[],int n) is to find the maximized difference between two subsets of negative and positive integers. It takes two arguments, one is the array itself and the other is its size n.

• Take a variable sum=0 to store the sum of all elements of the array.

• Starting from left, traverse each element of array using for loop ( i=0;i<n;i++ )

• If current element is negative (<0) make it positive by multiplying with -1.( arr[i]=arr[i]*-1 )

• Add each element to the sum.

• Return the sum as the maximum subset difference possible.

## Example

Live Demo

#include <stdio.h>
int subsetDifference(int arr[], int n){
int sum = 0;
for (int i = 0; i < n; i++){
if(arr[i]<0)
arr[i]=arr[i]*-1;
sum += arr[i];
}
return sum;
}
// Driver Code
int main(){
int arr[] = { -1, 3, 5, 17, -32, 12 };
int n = 6;
printf("Maximized difference between subsets : %d", subsetDifference(arr, n));
return 0;
}

## Output

If we run the above code it will generate the following output −

Maximized difference between two subsets: 70
Published on 17-Aug-2020 12:01:35