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

We are given an array of positive and negative integers. The task is to find the maximum difference between two subsets where one contains positive numbers and the other contains negative numbers. The maximum difference is achieved by taking all positive numbers in one subset and all negative numbers in the other subset, then calculating (sum of positives) − (sum of negatives). Since subtracting negatives effectively adds them, we can convert all negatives to positives and sum all elements.

Syntax

int maximizeSubsetDifference(int arr[], int n);

Example Input and Output

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

Output − Maximized difference between two subsets − 39

Explanation − Positive subset {0, 8, 10, 12} sum = 30, Negative subset {-2, -3, -4} sum = -9. Maximum difference = 30 - (-9) = 39

Approach

  • Take an integer array with positive and negative integers
  • Initialize sum = 0 to store the total
  • Traverse each element of the array
  • If current element is negative, convert it to positive by multiplying with -1
  • Add each element to the sum
  • Return the sum as the maximum possible subset difference

Example

#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;
}

int main() {
    int arr[] = { -1, 3, 5, 17, -32, 12 };
    int n = 6;
    
    printf("Array elements: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
    
    printf("Maximized difference between subsets: %d<br>", subsetDifference(arr, n));
    return 0;
}
Array elements: -1 3 5 17 -32 12 
Maximized difference between subsets: 70

How It Works

The algorithm works by recognizing that the maximum difference occurs when we separate positive and negative numbers into different subsets. Since we want to maximize (positive sum) − (negative sum), we effectively want to maximize (positive sum) + |negative sum|, which is simply the sum of absolute values of all elements.

Conclusion

This approach efficiently finds the maximum subset difference by converting all negative numbers to positive and summing all elements. The time complexity is O(n) and space complexity is O(1).

Updated on: 2026-03-15T13:02:44+05:30

348 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements