Skip to content

Commit

Permalink
Merge pull request #188 from PadmeshSharma/patch-2
Browse files Browse the repository at this point in the history
Create Book Allocation Problem.cpp
  • Loading branch information
panditakshay402 committed Oct 22, 2023
2 parents 9c5c3f0 + 61a26ff commit 69c69a8
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions C++/Book Allocation Problem.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
#include<vector>
using namespace std;

bool isPossible(vector<int> arr, int n, int m, int mid) {
int studentCount = 1;
int pageSum = 0;
//cout << "checking for mid "<< mid <<endl;

for(int i = 0; i<n; i++) {
if(pageSum + arr[i] <= mid) {
pageSum += arr[i];
}
else
{
studentCount++;
if(studentCount > m || arr[i] > mid ) {
return false;
}
pageSum = arr[i];
}
if(studentCount > m) {
return false;
}
//cout << " for i " << i << " Student "<< studentCount << " pageSum " << pageSum << endl;
}
return true;
}

int allocateBooks(vector<int> arr, int n, int m) {
int s = 0;
int sum = 0;

for(int i = 0; i<n; i++) {
sum += arr[i];
}
int e = sum;
int ans = -1;
int mid = s + (e-s)/2;

while(s<=e)
{
if(isPossible(arr,n,m,mid)) {
//cout<<" Mid returned TRUE" << endl;
ans = mid;
e = mid - 1;
}
else
{
s = mid + 1;
}
mid = s + (e-s)/2;
}
return ans;
}

0 comments on commit 69c69a8

Please sign in to comment.