Minimum decrements required such that sum of all adjacent pairs in an Array does not exceed K | Java program to implement the above approach ; 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
import java . util . * ; class GFG { static int minimum_required_operations ( int arr [ ] , int n , int k ) { int answer = 0 ; long mod = 1000000007 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] + arr [ i + 1 ] > k ) { if ( arr [ i ] > k ) { answer += ( arr [ i ] - k ) ; arr [ i ] = k ; } answer += ( arr [ i ] + arr [ i + 1 ] ) - k ; arr [ i + 1 ] = ( k - arr [ i ] ) ; answer %= mod ; } } return answer ; } public static void main ( String [ ] args ) { int a [ ] = { 9 , 50 , 4 , 14 , 42 , 89 } ; int k = 10 ; int n = a . length ; System . out . print ( minimum_required_operations ( a , n , k ) ) ; } }