1495. Calm Batches
A warehouse receives items in a fixed order, and nums[i] is the size of the i-th item. The items must be packed, without reordering, into at most k batches, each batch being a non-empty run of neighbouring items; some batches may stay unused. The spread of a batch is its largest size minus its smallest size.
Return the smallest possible value of the largest spread over all batches, minimised over every way to split nums into at most k batches. A bigger allowed spread never needs more batches, so binary search the spread X and greedily extend the current batch while its running maximum minus minimum stays within X, opening a new batch only when forced. Target O(n log(max - min)) time and O(1) extra space.
Example 1
- Input:
- nums = [7,2,9,4,12,3], k = 2
- Output:
- 9
- Explanation:
Split into [7, 2, 9, 4] with spread 7 and [12, 3] with spread 9; no two-batch split keeps every spread below 9.
Example 2
- Input:
- nums = [5,5,5,5], k = 1
- Output:
- 0
- Explanation:
All items are equal, so a single batch has spread 0.
Example 3
- Input:
- nums = [1,100], k = 2
- Output:
- 0
- Explanation:
Two batches of one item each both have spread 0.
Constraints
1 ≤ n ≤ 105; 0 ≤ nums[i] ≤ 109; 1 ≤ k ≤ n
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 6,000 msC++ 1,500 msJava 3,000 msJavaScript 3,000 msTypeScript 3,000 ms
Expected complexity
- Time
- O(n log(max - min))
- Space
- O(1)