-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplitArraySum.cpp
More file actions
30 lines (30 loc) · 849 Bytes
/
Copy pathSplitArraySum.cpp
File metadata and controls
30 lines (30 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
int canSplit(vector<int>& nums, int maxSumLimit) {
int subarrays = 1;
long long currentSum =0;
for (int i=0;i<nums.size();i++){
if(currentSum+nums[i]<=maxSumLimit) {
currentSum += nums[i];
}else {
subarrays++;
currentSum = nums[i];
}
}
return subarrays;
}
int splitArray(vector<int>& nums, int k) {
int low = *max_element(nums.begin(), nums.end());
long long high = accumulate(nums.begin(), nums.end(), 0LL);
while (low<=high) {
int mid = low+(high-low)/2;
int requiredSubarrays = canSplit(nums,mid);
if(requiredSubarrays<=k) {
high = mid-1;
}else {
low = mid+1;
}
}
return low;
}
};