Minimum operations to make sum of neighbouring elements <= X | Function to return the minimum number of operations required ; To store total operations required ; First make all elements equal to x which are currenctly greater ; Left scan the array ; Update the current element such that neighbouring sum is < x ; Driver code
def MinOperations ( n , x , arr ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > x ) : NEW_LINE INDENT difference = arr [ i ] - x NEW_LINE total = total + difference NEW_LINE arr [ i ] = x NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT LeftNeigbouringSum = arr [ i ] + arr [ i - 1 ] NEW_LINE if ( LeftNeigbouringSum > x ) : NEW_LINE INDENT current_diff = LeftNeigbouringSum - x NEW_LINE arr [ i ] = max ( 0 , arr [ i ] - current_diff ) NEW_LINE total = total + current_diff NEW_LINE DEDENT DEDENT return total NEW_LINE DEDENT X = 1 NEW_LINE arr = [ 1 , 6 , 1 , 2 , 0 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinOperations ( N , X , arr ) ) NEW_LINE