Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K | Function to calculate the minimum number of operations required ; Stores the total number of operations ; Iterate over the array ; If the sum of pair of adjacent elements exceed k . ; If current element exceeds k ; Reduce arr [ i ] to k ; Update arr [ i + 1 ] accordingly ; Update answer ; Driver Code
def minimum_required_operations ( arr , n , k ) : NEW_LINE INDENT answer = 0 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i ] + arr [ i + 1 ] > k : NEW_LINE INDENT if arr [ i ] > k : NEW_LINE INDENT answer += ( arr [ i ] - k ) NEW_LINE arr [ i ] = k NEW_LINE DEDENT answer += ( arr [ i ] + arr [ i + 1 ] ) - k NEW_LINE arr [ i + 1 ] = ( k - arr [ i ] ) NEW_LINE answer %= mod NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT a = [ 9 , 50 , 4 , 14 , 42 , 89 ] NEW_LINE k = 10 NEW_LINE print ( minimum_required_operations ( a , len ( a ) , k ) ) NEW_LINE