# Find the maximum cost of an array of pairs choosing at most K pairs in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of pairs A; we have to find the maximum cost for selecting at most K pairs. In this case, the cost of an array of pairs type elements is the product of the sum of first elements of the selected pair and the smallest among the second elements of the selected pairs. As an example, if these pairs are selected (4, 8), (10, 3) and (3, 6), then the cost will be (4+10+3)*(3) = 51, for K=3

So, if the input is like A = [(15, 5), (65, 25), (35, 20), (20, 5), (35, 20), (15, 18), (3, 8), (12, 17)], K = 4, then the output will be 2700

To solve this, we will follow these steps −

• res := 0, sum = 0

• N := size of A

• Define one set of pairs called my_set

• sort the array A based on the second value of each pair

• for initialize i := N - 1, when i >= 0, update (decrease i by 1), do −

• make a pair (first element of A[i], i) and insert into my_set

• sum := sum + first element of A[i]

• while size of my_set > K, do −

• it := first element of my_set

• sum := sum - first of it

• delete it from my_set

• res := maximum of res and sum * second of A[i]

• return res

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool compactor(const pair<int, int>& a,const pair<int, int>& b) {
return (a.second < b.second);
}
int get_maximum_cost(vector<pair<int, int> > &A, int K){
int res = 0, sum = 0;
int N = A.size();
set<pair<int, int>> my_set;
sort(A.begin(), A.end(), compactor);
for (int i = N - 1; i >= 0; --i) {
my_set.insert(make_pair(A[i].first, i));
sum += A[i].first;
while (my_set.size() > K) {
auto it = my_set.begin();
sum -= it->first;
my_set.erase(it);
}
res = max(res, sum * A[i].second);
}
return res;
}
int main() {
vector<pair<int, int> > arr = {{ 15, 5}, { 65, 25}, { 35, 20}, { 20, 5}, { 35, 20}, { 15, 18}, { 3, 8 }, {12, 17}};
int K = 4;
cout << get_maximum_cost(arr, K);
}

## Input

{{15, 5},{65, 25}, { 35, 20}, { 20, 5}, { 35, 20}, { 15, 18}, { 3, 8
}, {12, 17}}, 4

## Output

2700