
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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
- Related Articles
- Maximum Weight Difference in C++ Program
- Maximum weight transformation of a given string in C++
- Difference Between Mass and Weight
- Write the difference between weight and mass.
- Difference Between Free Weights and Weight Machines
- Find Maximum difference pair in Python
- Maximum weight path ending at any element of last row in a matrix in C++
- Python - Maximum difference across lists
- Maximum Difference Between Node and Ancestor in C++
- Find Maximum difference between tuple pairs in Python
- Maximum difference between a number JavaScript
- Maximum sum of pairs with specific difference in C++
- Maximum sum of difference of adjacent elements in C++
- Font Weight in CSS
- Maximum difference between two subsets of m elements in C
