Sudo Placement | Placement Tour | Python Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget
value = 0 NEW_LINE def canBeOptimalValue ( K : int , arr : list , N : int , B : int ) -> bool : NEW_LINE INDENT global value NEW_LINE tmp = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) NEW_LINE DEDENT tmp . sort ( ) NEW_LINE value = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT value += tmp [ i ] NEW_LINE DEDENT return value <= B NEW_LINE DEDENT def findNoOfElementsandValue ( arr : list , N : int , B : int ) : NEW_LINE INDENT global value NEW_LINE ans = 0 NEW_LINE value = 0 NEW_LINE while start <= end : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if canBeOptimalValue ( mid , arr , N , B ) : NEW_LINE INDENT ans = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT canBeOptimalValue ( ans , arr , N , B ) NEW_LINE print ( ans , value ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 6 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE B = 90 NEW_LINE findNoOfElementsandValue ( arr , N , B ) NEW_LINE DEDENT