Award Budget Cuts

The awards committee of your alma mater (i.e. your college/university) asked for your assistance with a budget allocation problem they’re facing. Originally, the committee planned to give N research grants this year. However, due to spending cutbacks, the budget was reduced to newBudget dollars and now they need to reallocate the grants. The committee made a decision that they’d like to impact as few grant recipients as possible by applying a maximum cap on all grants. Every grant initially planned to be higher than cap will now be exactly cap dollars. Grants less or equal to cap, obviously, won’t be impacted.

Given an array grantsArray of the original grants and the reduced budget newBudget, write a function findGrantsCap that finds in the most efficient manner a cap such that the least number of recipients is impacted and that the new budget constraint is met (i.e. sum of the N reallocated grants equals to newBudget).

Analyze the time and space complexities of your solution.

Example:

1
2
3
4
5
input:  grantsArray = [2, 100, 50, 120, 1000], newBudget = 190

output: 47 # and given this cap the new grants array would be
# [2, 47, 47, 47, 47]. Notice that the sum of the
# new grants is indeed 190

Constraints:

[time limit] 5000ms

[input] array.double grantsArray

0 ≤ grantsArray.length ≤ 20
0 ≤ grantsArray[i]
[input] double newBudget

[output] double

Attempt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include <vector>

using namespace std;

double findGrantsCap( vector<int> grantsArray, int newBudget )
{
//sort(grantsArray);
int sum = 0;
int len = grantsArray.size();

double mean = newBudget / len;
//cout << "mean = " << mean << endl;
// get count and sum of values less than mean

int count = 0;
int rem_sum = 0;
for (auto e: grantsArray) {
if (e < mean) {
count++;
rem_sum += e;
}
}
cout << (newBudget - rem_sum) / (len - count) << endl;
return ((newBudget - rem_sum) / (len - count));


}

int main() {
findGrantsCap({2, 100, 50, 120, 1000}, 190);
return 0;
}

Fails a few test cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Time: 8ms
Passed: 2
Failed: 4
Test Case #1
Input: [2,4], 3,Expected: 1.5,Actual: 1
Test Case #2
Input: [2,4,6], 3,Expected: 1,Actual: 1
Test Case #3
Input: [2,100,50,120,167], 400,Expected: 128,Actual: 116
Test Case #4
Input: [2,100,50,120,1000], 190,Expected: 47,Actual: 47
Test Case #5
Input: [21,100,50,120,130,110], 140,Expected: 23.8,Actual: 23
Test Case #6
Input: [210,200,150,193,130,110,209,342,117], 1530,Expected: 211,Actual: 204