Maximum Weight Difference in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find Maximum Weight Difference.

For this we will be provided with an integer and a value K. Our task is to choose K elements from the array such that their sum and the sum of rest elements is maximum.

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
//finding the maximum of two values
int max(int a, int b) {
   return a > b ? a : b;
}
int solve(int array[], int n, int k) {
   sort(array, array + n);
   int sum = 0, sum1 = 0, sum2 = 0;
   for (int i = 0; i < n; i++) {
      sum += array[i];
   }
   for (int i = 0; i < k; i++) {
      sum1 += array[i];
   }
   //sum of remaining elements
   for (int i = k; i < n; i++) {
      sum2 += array[i];
   }
   return max(abs(sum1 - (sum - sum1)), abs(sum2 - (sum - sum2)));
}
int main() {
   int k = 2;
   int array[] = { 8, 4, 5, 2, 10 };
   int n = sizeof(array) / sizeof(array[0]);
   cout << solve(array, n, k);
   return 0;
}

Output

17
raja
Published on 27-Jul-2020 12:09:55
Advertisements