← DiffPush

Book allocation

Baseline Binary Search · In Search Space O(N log S), where S is the total page count · O(1)

Balancing Shelves Along One Reading Order

A library must distribute a fixed sequence of volumes onto m reading desks. The sequence cannot be reordered, every desk gets a non-empty consecutive block, and the fairest split minimizes the page count on the most-loaded desk. Compute that minimized maximum load, or report that there are more desks than volumes.

Input: An integer N, an array A of N positive page counts (in fixed order), and an integer M, the number of students.

Output: The minimum possible value of the maximum pages assigned to any student, or -1 when M > N.

Constraints

Examples

Example 1

Input: {"N":4,"A":[12,34,67,90],"M":2}
Output: 113
Splitting after the third volume balances 113 against 90, and every other split leaves a heavier desk.

Example 2

Input: {"N":5,"A":[25,46,28,49,24],"M":4}
Output: 71
Blocks 25+46, 28, 49 and 24 cap the load at 71, the best the order allows.

Solve this in your browser →

Also on LeetCode ↗