Maximum items that can be bought from the cost Array based on given conditions | Function to find the maximum number of items that can be bought from the given cost array ; Sort the given array ; Variables to store the prefix sum , answer and the counter variables ; Initializing the first element of the prefix array ; If we can buy at least one item ; Iterating through the first K items and finding the prefix sum ; Check the number of items that can be bought ; Finding the prefix sum for the remaining elements ; Check the number of iteams that can be bought ; Driver code
def number ( a , n , p , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE pre = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pre . append ( 0 ) NEW_LINE DEDENT ans = 0 NEW_LINE val = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE pre [ 0 ] = a [ 0 ] NEW_LINE if pre [ 0 ] <= p : NEW_LINE INDENT ans = 1 NEW_LINE DEDENT for i in range ( 1 , k - 1 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + a [ i ] NEW_LINE if pre [ i ] <= p : NEW_LINE INDENT ans = i + 1 NEW_LINE DEDENT DEDENT pre [ k - 1 ] = a [ k - 1 ] NEW_LINE for i in range ( k - 1 , n ) : NEW_LINE INDENT if i >= k : NEW_LINE INDENT pre [ i ] += pre [ i - k ] + a [ i ] NEW_LINE DEDENT if pre [ i ] <= p : NEW_LINE INDENT ans = i + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE arr = [ 2 , 4 , 3 , 5 , 7 ] NEW_LINE p = 11 NEW_LINE k = 2 NEW_LINE print ( number ( arr , n , p , k ) ) NEW_LINE