# C++ Program to count minimum problems to be solved to make teams

Suppose we have an array A with n elements. There are n students in a university, n is even. The i-th student has programming skill equal to A[i]. The team leader wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal. Students can solve problems to increase their skill. If they solve one problem, their skill will be increased by 1. We have to find the minimum total number of problems students should solve to form exactly n/2 teams

## Problem Category

This problem falls under sorting problems. Sorting is a very common problem while we are talking about different problem solving algorithms in computer science. As the name suggests, sorting indicates arranging a set of data into some fashion. We can arrange them in nondecreasing order or non-increasing order in general. Otherwise sorting can be also takes place in a pre-defined manner. For the string based problems, sometimes we refer lexicographical sorting to arrange letters in dictionary fashion. There are plenty of different sorting techniques with certain variations and their time and space complexity. To date, the lower-bound of the time complexity for comparison based sorting techniques is O(n*log n). However there are some mechanical sorting techniques like bucket sort, radix sort, counting sorts are there whose time complexity is linear O(n) in time. For further reading, please follow the link below −

https://www.tutorialspoint.com/data_structures_algorithms/sorting_algorithms.htm

So, if the input of our problem is like A = [5, 10, 2, 3, 14, 5], then the output will be 5, because the teams can be (2,3), (0,5) and (1,4). Then, to form the first team the third student should solve 1 problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve 4 problems.

## Steps

To solve this, we will follow these steps −

n := size of A
cnt := 0
sort the array A
for initialize i := 0, when i < n, update i := i + 2, do:
cnt := cnt + A[i + 1] - A[i]
return cnt

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A){
int n = A.size();
int cnt = 0;
sort(A.begin(), A.end());
for (int i = 0; i < n; i += 2)
cnt += A[i + 1] - A[i];
return cnt;
}
int main(){
vector<int> A = { 5, 10, 2, 3, 14, 5 };
cout << solve(A) << endl;
}

## Input

{ 5, 10, 2, 3, 14, 5 }

## Output

5