AlgoPlus v0.1.0
Loading...
Searching...
No Matches
split_K_max.h
1#ifndef SPLIT_K_MAX_H
2#define SPLIT_K_MAX_H
3
4#ifdef __cplusplus
5#include <algorithm>
6#include <climits>
7#include <iostream>
8#include <numeric>
9#include <vector>
10#endif
11
12namespace helpers {
22bool check(std::vector<int>& v, int mid, int K) {
23 int sum = 0;
24 int splits = 1;
25
26 for (int i = 0; i < int(v.size()); i++) {
27 if (v[i] > mid) {
28 return false;
29 }
30
31 sum += v[i];
32 if (sum > mid) {
33 splits++;
34 sum = v[i];
35 }
36 }
37
38 return (splits <= K) ? true : false;
39}
40} // namespace helpers
41
52int minimum_max_sub_sum(std::vector<int>& v, int K) {
53 int start = v[0];
54 int end = std::accumulate(v.begin(), v.end(), 0);
55
56 int ans = INT_MAX;
57 while (start <= end) {
58 int mid = start + (end - start) / 2;
59
60 if (helpers::check(v, mid, K)) {
61 ans = mid;
62 end = mid - 1;
63 } else {
64 start = mid + 1;
65 }
66 }
67
68 return ans;
69}
70
71#endif