Advertisement
Iam_Sandeep

ALllocate minimum number of pages

Feb 11th, 2022
719
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. https://practice.geeksforgeeks.org/problems/allocate-minimum-number-of-pages0937/1#
  2. NOTE:
  3. we use "return True if cnt<=M becasue it gives the directions to reduce search space.
  4. The func allocate  is giving directions for search space.(VVIMP)
  5.  
  6. class Solution:
  7.    
  8.    #Function to find minimum number of pages.
  9.    def findPages(self,A, N, M):
  10.        #code here
  11.        def allocate(barrier):
  12.            cur=0
  13.            students=1
  14.            for i in range(N):
  15.                if A[i]>barrier:
  16.                    return False
  17.                if cur+A[i]<=barrier:
  18.                    cur+=A[i]
  19.                else:
  20.                    students+=1
  21.                    cur=A[i]
  22.            return True if students<=M else False
  23.            
  24.        
  25.        ans=float('inf')
  26.        l,h=min(A),sum(A)
  27.        while l<=h:
  28.            m=(l+h)//2
  29.            if allocate(m):
  30.                ans=min(ans,m)
  31.                h=m-1
  32.            else:
  33.                l=m+1
  34.        return ans
  35.                
  36.            
  37.  
  38.  
  39. #{
  40. #  Driver Code Starts
  41. #Initial Template for Python 3
  42.  
  43. #contributed by RavinderSinghPB
  44. if __name__=='__main__':
  45.    t=int(input())
  46.    for _ in range(t):
  47.        
  48.        n=int(input())
  49.        
  50.        arr=[int(x) for x in input().strip().split()]
  51.        m=int(input())
  52.        
  53.        ob=Solution()
  54.        
  55.        print(ob.findPages(arr,n,m))
  56. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement