Minimum operations to make sum of neighbouring elements <= X | Java implementation of the approach ; 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
class GFG { static int MinOperations ( int n , int x , int [ ] arr ) { int total = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( arr [ i ] > x ) { int difference = arr [ i ] - x ; total = total + difference ; arr [ i ] = x ; } } for ( int i = 1 ; i < n ; ++ i ) { int LeftNeigbouringSum = arr [ i ] + arr [ i - 1 ] ; if ( LeftNeigbouringSum > x ) { int current_diff = LeftNeigbouringSum - x ; arr [ i ] = Math . max ( 0 , arr [ i ] - current_diff ) ; total = total + current_diff ; } } return total ; } public static void main ( String args [ ] ) { int X = 1 ; int arr [ ] = { 1 , 6 , 1 , 2 , 0 , 4 } ; int N = arr . length ; System . out . println ( MinOperations ( N , X , arr ) ) ; } }