Algorithm
Kevin Sun wants to move his precious collection of n cowbells from Naperthrill to Exeter, where there is actually grass instead of corn. Before moving, he must pack his cowbells into k boxes of a fixed size. In order to keep his collection safe during transportation, he won't place more than two cowbells into a single box. Since Kevin wishes to minimize expenses, he is curious about the smallest size box he can use to pack his entire collection.
Kevin is a meticulous cowbell collector and knows that the size of his i-th (1 ≤ i ≤ n) cowbell is an integer si. In fact, he keeps his cowbells sorted by size, so si - 1 ≤ si for any i > 1. Also an expert packer, Kevin can fit one or two cowbells into a box of size s if and only if the sum of their sizes does not exceed s. Given this information, help Kevin determine the smallest s for which it is possible to put all of his cowbells into k boxes of size s.
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 2·k ≤ 100 000), denoting the number of cowbells and the number of boxes, respectively.
The next line contains n space-separated integers s1, s2, ..., sn (1 ≤ s1 ≤ s2 ≤ ... ≤ sn ≤ 1 000 000), the sizes of Kevin's cowbells. It is guaranteed that the sizes si are given in non-decreasing order.
Print a single integer, the smallest s for which it is possible for Kevin to put all of his cowbells into k boxes of size s.
2 1
2 5
7
4 3
2 3 5 9
9
3 2
3 5 7
8
In the first sample, Kevin must pack his two cowbells into the same box.
In the second sample, Kevin can pack together the following sets of cowbells: {2, 3}, {5} and {9}.
In the third sample, the optimal solution is {3, 5} and {7}.
Code Examples
#1 Code Example with C++ Programming
Code -
C++ Programming
#include <bits/stdc++.h>
using namespace std;
int const N = 1e5 + 1;
int n, k, a[N];
bool can(int mid) {
int have = k;
for(int i = 0, j = n - 1; i <= j; ++i, --j) {
if(i == j) {
if(a[i] > mid)
return false;
--have;
break;
} else {
if(a[i] + a[j] <= mid)
--have;
else {
for(int k = i; k <= j; ++k) {
if(k + 1 <= j && a[k] + a[k + 1] <= mid) {
++k, --have;
continue;
}
if(a[k] > mid)
return false;
--have;
}
break;
}
}
}
return have >= 0;
}
int main() {
cin >> n >> k;
for(int i = 0; i < n; ++i)
cin >> a[i];
if(k >= n) {
cout << a[n - 1] << endl;
return 0;
}
int rem = (k * 2) - n;
n -= rem, k -= rem;
int l = 1, r = 3000000, mid, res = -1;
while(l <= r) {
mid = (l + r) / 2;
if(can(mid))
res = mid, r = mid - 1;
else
l = mid + 1;
}
cout << max(res, a[n + rem - 1]> << endl;
return 0;
}
Copy The Code &
Try With Live Editor
Input
2 5
Output
Demonstration
Codeforces Solution-More Cowbell-Solution in C, C++, Java, Python