C++ Program to find ways to get a and b numbers of chores by brothers

Suppose we have an array A with n elements and two values a and b. Amal and Bimal are two brothers. Their parents left them home alone and commissioned them to do n chores. Each chore has its complexity. The complexity of the i-th chore equals A[i]. Amal is older, he wants to take the chores with complexity larger than some value x (A[i] > x) to leave to Bimal the chores with complexity less than or equal to x (A[i] ≤ x). Amal will do exactly a number of chores and Bimal will do exactly b number of chores (a + b = n). We have to find the number of ways x can be chosen, so that Amal got exactly a number of chores and Bimal got exactly b number of chores?

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 −


So, if the input of our problem is like A = [6, 2, 3, 100, 1]; a = 2; b = 3, then the output will be 3, because the possible values of x are 3, 4 or 5.


To solve this, we will follow these steps −

sort the array A
return A[b] - A[b - 1]


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int a, int b){
   sort(A.begin(), A.end());
   return A[b] - A[b - 1];
int main(){
   vector<int> A = { 6, 2, 3, 100, 1 };
   int a = 2;
   int b = 3;
   cout << solve(A, a, b) << endl;


{ 6, 2, 3, 100, 1 }, 2, 3