Choose an ordering of the array, subtract elements from n in that order until n drops to 0 or below, and report the smallest achievable result.
Medium4GreedySortingInterviewNo attempts yetTime limit1sMemory limit512 MBHere is the code of the getMin( ) function.
int getMin(int n, int arr[]){
arr2 = rearrange(arr);
for(int i = 0; i < arr2.length(); i = i+1){
n = n-arr2[i];
if (n <= 0) break;
}
return n;
}
getMin( ) takes an integer n and an integer array arr, then calls rearrange( ). The rearrange( ) function takes an integer array and returns a new array. The new array holds the same members as the old one, and the position of each member may change.
How you write rearrange( ) is not judged. Choose the arrangement that makes the return value of getMin( ) as small as possible, and report that return value.
The first line contains the number of test cases T. (1≤T≤10)
Each test case takes two lines. The first line contains the integer n and the length k of the array arr, separated by a space. (0≤n≤10000, 0≤k≤10000) The second line contains k integers, arr[0] through arr[k-1], separated by spaces. (0≤arr[i]≤1000000) When k is 0, the second line is empty.
For each test case, print the smallest value getMin( ) can return, one per line. The value may be negative.
In the second test case of the example, you send [70, 60, 80] to rearrange( ) and it returns [80, 70, 60]. Then 100−80=20 and 20−70=−50, so the loop stops and the function returns −50. More than one arrangement can reach the minimum, but the value you print is that single minimum.