


You are the Librarian of the Ninja library. There are ‘N’ books available in the library and ‘B’ ninjas want to read the books. You know the number of pages in each book and you have to allocate the books to the ‘B’ ninjas in such a way that the maximum number of pages allocated to a ninja is minimum.
Note
A book will be allocated to exactly one ninja.
At least one book has to be allocated to a ninja.
Allotment of the books should be done in a contiguous manner. For example, a ninja can not be allocated book 2 and book 4, skipping book 3.
The task is to return the minimum of the maximum number of pages allocated to a ninja.
Input Format:
The first line contains a single integer T representing the number of test cases.
The T-test cases are as follows:
The first line contains two space-separated integers ‘N’ and ‘B’ denoting the number of books, and the number of ninjas, respectively.
The second line contains N space-separated integers, where the ith element is the number of pages in the ith book.
Output Format :
The first and only line of output contains an integer denoting the minimum of the maximum number of pages allocated to a ninja.
The output of every test case is printed in a separate line.
Note:
Return -1 if it is impossible to allocate the books to all the ninjas.
Constraints:
1 <= T <= 10
1 <= N <= 10^4
1 <= B <= 10^2
0 <= pages <= 10^3
where T is the number of test cases, ‘N’ is the number of books, ‘B’ is the number of ninjas and ‘pages’ is the number of pages in each book.
1
4 2
10 20 30 40
60
There are two ninjas and these are the following ways to allocate the books between them.
Way 1 ⇒ Ninja 1: [10] and Ninja 2: [20, 30, 40]
Way 2 ⇒ Ninja 2: [10, 20], and Ninja 2: [30, 40]
Way 3 ⇒ Ninja 1: [10, 20, 30], and Ninja 2: [40]
Among all the ways, way 3 is the best way because the maximum number of pages allocated to a ninja is 60. In way 1 and way 2, the maximum number of pages allocated to a ninja is 90, and 70, respectively. Hence, 60 is the answer.
1
5 6
10 20 30 40 50
-1
Since we can not allocate at-least one book to every ninja, the answer is -1.
Consider all the possible ways.
Let’s look at both conditions:
O(N * sumOfPages), where N is the number of books and ‘sumOfPages’ is the sum of the pages of all the books.
We are looping on a range(‘maxPages’ to ‘sumOfPages’)[ O(sumOfPages) time] and for every index, we are checking if it is possible to assign the books to all the ninjas such that the maximum possible pages allocated to a ninja is less than or equal to the current index [O(N) time]. Thus, the final time complexity is O(N) * O(sumOfPages) = O(N * sumOfPages).
O(1)
Constant additional space is used.