Maximum possible difference of two subsets of an array | CPP find maximum difference of subset sum ; function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxDiff ( int arr [ ] , int n ) { int result = 0 ; sort ( arr , arr + n ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] != arr [ i + 1 ] ) result += abs ( arr [ i ] ) ; else i ++ ; } if ( arr [ n - 2 ] != arr [ n - 1 ] ) result += abs ( arr [ n - 1 ] ) ; return result ; } int main ( ) { int arr [ ] = { 4 , 2 , -3 , 3 , -2 , -2 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ Difference ▁ = ▁ " << maxDiff ( arr , n ) ; return 0 ; }