-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAllocate Minimum Pages.cpp
83 lines (74 loc) · 1.8 KB
/
Allocate Minimum Pages.cpp
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//{ Driver Code Starts
// Initial function template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
bool isPossible(vector<int>& arr , int k , int mid){
int count = 1, sum = 0;
for(int i = 0; i<arr.size(); i++){
if(sum + arr[i] <=mid){
sum+=arr[i];
}else {
count++;
if(count >k || arr[i] > mid) return false;
sum = 0;
sum+= arr[i];
}
}
return true;
}
int findPages(vector<int> &arr, int k) {
// code here
if(k > arr.size() ) return -1;
int sum = 0;
for(int i = 0; i<arr.size(); i++){
sum+=arr[i];
}
int start = 0, end = sum;
int ans = -1;
while(start <= end){
int mid = start + (end- start)/2;
if(isPossible(arr,k,mid)){
ans = mid;
end = mid-1;
}else {
start = mid+1;
}
}
return ans;
}
};
//{ Driver Code Starts.
int main() {
int test_case;
cin >> test_case;
cin.ignore();
while (test_case--) {
int d;
vector<int> arr, brr, crr;
string input;
getline(cin, input);
stringstream ss(input);
int number;
while (ss >> number) {
arr.push_back(number);
}
getline(cin, input);
ss.clear();
ss.str(input);
while (ss >> number) {
crr.push_back(number);
}
d = crr[0];
int n = arr.size();
Solution ob;
int ans = ob.findPages(arr, d);
cout << ans << endl;
cout << "~"
<< "\n";
}
return 0;
}
// } Driver Code Ends