Problem 106
Capacity To Ship Packages
Medium · 20 pts · Array, Binary Search, Greedy
Problem
N packages with weights W[0..N-1] must be shipped in the given order within D days. Each day the ship is loaded with the next packages in line, as many as fit without the total weight exceeding the ship's capacity, and the order may not be changed. Find the smallest capacity that ships all the packages within D days. The capacity must be at least the heaviest package and at most the total weight. A larger capacity never needs more days, so binary search on the capacity, simulating the loading greedily to count the days for each candidate.
Input
First line: integers N and D. Second line: N package weights.
Output
Print the minimum ship capacity.
Constraints
1 <= D <= N <= 50000; 1 <= W[i] <= 500
Example input
10 5 1 2 3 4 5 6 7 8 9 10
Example output
15
Explanation
With capacity 15, the days are 1+2+3+4+5 = 15, then 6+7 = 13, then 8, then 9, then 10: exactly 5 days. With capacity 14 it would take 6 days, so the answer is 15.