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).Example:
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
My approach:
import java.util.Arrays;
class Solution {
static double findGrantsCap(double[] grantsArray, double newBudget) {
// your code goes here
int len = grantsArray.length;
Arrays.sort(grantsArray);
//Calculate the newBudget
double modBudget = newBudget;
double cap;
double sum = 0;
double avg;
for (double elem: grantsArray)
sum += elem;
avg = sum/len;
if( avg == (int)newBudget)
return (newBudget)/len;
else
{
Arrays.sort(grantsArray);
modBudget -= grantsArray[0];
cap = modBudget/(len - 1);
for( int i = 1; i < len-1; i++ )
{
System.out.println(cap);
if( (int)cap > grantsArray[i] )
{
modBudget -= grantsArray[i];
cap = modBudget/(len - i - 1);
}
}
}
return cap;
}
public static void main(String[] args) {
double [] grantsArray = {2,100,50,120,167};
double newBudget = 400;
System.out.println(findGrantsCap(grantsArray,newBudget));
}
}
I have the following questions with regards to the above code:
How can I further improve the algorithm, time or space wise?
Is my solution satisfying all the test cases and why is it failing if any?
Have I made any gross violations to the Java Coding conventions?