Maximum Weight Difference in C++ Program


In this problem, we are given an array arr[] and a number M. Our task is to create a program to calculate the Maximum Weight Difference in C++.

Problem description

We will find M elements from the array such that the absolute difference
between the sum and the sum of the rest elements is maximum.

Let’s take an example to understand the problem,

Input

arr[] = {3, 1, 6, 9, 4} M = 3

Output

15

Explanation

We will consider 4,6,9. The sum is 19. The absolute difference with the sum of rest numbers is

|19 − 4| = 15

Solution Approach

A simple solution to the problem is by finding all subsequences of the array, finding the sum elements of the subarray, and the rest. And return the maximum difference.

A more efficient solution is found by using the fact that maximum weight difference i.e. difference of the sum of elements and the rest is maximum if we consider m maximum elements or m minimum elements for subsequence.

So, we will check for the maximum sum difference for a subsequence of m largest elements and rest array or subsequence of m smallest elements and rest array.

And return the maximum of both.

Algorithm

Initialize

maxSum , maxSumDiff, minSumDiff

Step 1

sort the array in descending order.

Step 2

Loop for i −> 0 to n

Step 2.1

if (i < m) −> maxSumDiff += arr[i]

Step 2.2

else −> maxSumDiff −= arr[i]

Step 2

Loop for i −> n to 0

Step 2.1

if (i > m) −> minSumDiff += arr[i]

Step 2.2

else −> minSumDiff −= arr[i]

Step 3

if maxSumDiff > minSumDiff −> maxSum = maxSumDiff.

Step 4

if maxSumDiff < minSumDiff −> maxSum = minSumDiff.

Step 5

return maxSum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int maxWeightDifference(int arr[], int N, int M){
   int maxabsDiff = −1000;
   sort(arr, arr + N);
   int sumMin = 0, sumMax = 0, arrSum = 0;
   for(int i = 0; i < N; i++){
      arrSum += arr[i];
      if(i < M)
         sumMin += arr[i];
      if(i >= (N−M))
         sumMax += arr[i];
   }
   maxabsDiff = max(abs(sumMax − (arrSum − sumMax)), abs(sumMin −
   (arrSum − sumMin)));
   return maxabsDiff;
}
int main(){
   int arr[] = {3, 1, 6, 9, 4} ;
   int M = 3;
   int N = sizeof(arr)/sizeof(arr[0]);
   cout<<"The maximum weight difference is "<<maxWeightDifference(arr,N, M);
   return 0;
}

Output

The maximum weight difference is 15

Updated on: 09-Dec-2020

160 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements