Maximum Weight Difference in C++


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 Statement

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

Let’s take an example to understand the problem,

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

Ouput: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

The solution to the problem is based on the fact that the maximum difference is possible only in the case of M largest numbers or M smallest numbers. And we need to check both conditions and compare the absolute difference to find the final result. To ease the process of finding the M largest/smallest numbers, we will sort the array and then do the calculations on K largest and smallest numbers.

Example

 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-Oct-2020

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements