text: 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
code: function MinOperations ( n , x , arr ) { let total = 0 ; for ( let i = 0 ; i < n ; ++ i ) { if ( arr [ i ] > x ) { let difference = arr [ i ] - x ; total = total + difference ; arr [ i ] = x ; } } for ( let i = 1 ; i < n ; ++ i ) { let LeftNeigbouringSum = arr [ i ] + arr [ i - 1 ] ; if ( LeftNeigbouringSum > x ) { let current_diff = LeftNeigbouringSum - x ; arr [ i ] = Math . max ( 0 , arr [ i ] - current_diff ) ; total = total + current_diff ; } } return total ; } let X = 1 ; let arr = [ 1 , 6 , 1 , 2 , 0 , 4 ] ; let N = arr . length ; document . write ( MinOperations ( N , X , arr ) + " " ) ;