Day34

C++ code posted
created at 02 May 12:10

Edit | Back
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
class Solution {
    private:
    int ok(vector<int> arr,int pages)
    {
        int cnt=1,curr=0;
        for(int i:arr)
        {
            if(curr+i<=pages)
            {
                curr+=i;
            }
            else
            {
                cnt++;
                curr=i;
            }
        }
        return cnt;
    }
  public:
    int findPages(vector<int> &arr, int k) {
        // code here
        int n=arr.size();
        if(n<k) return -1;
        if(k==1) return accumulate(arr.begin(),arr.end(),0);
        int l=*max_element(arr.begin(),arr.end());
        int h=accumulate(arr.begin(),arr.end(),0);
        int ans=INT_MAX;
        while(l<=h)
        {
            int m=l+(h-l)/2;
            int s=ok(arr,m);
            if(s<=k)
            {
                ans=min(ans,m);
                h=m-1;
            }
            else
            {
              l=m+1;
            }
            
        }
        return ans==INT_MAX?-1:ans;
    }
};
1.01 KB in 3 ms with coderay