Minimize Maximum Difference of Elements in IntervalsHard

Minimize Maximum Difference of Elements in Intervals

HardPractice library · +30 XPheapssliding windowgreedy

Given an array of N integers, you need to partition it into K contiguous subarrays. Your goal is to minimize the maximum difference between the largest and smallest element within any subarray. Output this minimum possible maximum difference.

Input

The first line contains two integers N and K. The second line contains N space-separated integers, representing the array elements.

Output

Print a single integer: the minimum possible maximum difference.

Constraints

1 <= N <= 200000 1 <= K <= N 0 <= array elements <= 10^9

Time limit 2 s (native code; slower languages get more)Memory 256 MB15 hidden tests

Example 1

Input
5 2
1 5 2 8 3
Output
5

Partition into [1, 5, 2] and [8, 3]. Differences are 5-1=4 and 8-3=5. Max difference is 5. Another partition: [1, 5] and [2, 8, 3]. Differences are 5-1=4 and 8-2=6. Max difference is 6. Minimal max difference is 5.

Example 2

Input
7 3
10 20 30 5 15 25 40
Output
20

Partition [10, 20, 30], [5, 15, 25], [40]. Differences are 20, 20, 0. Max difference is 20. This is optimal.

Hints