Minimize insertions to make sum of every pair of consecutive array elements at most K | Function to count minimum number of insertions required to make sum of every pair of adjacent elements at most K ; Stores if it is possible to make sum of each pair of adjacent elements at most K ; Stores the count of insertions ; Stores the previous value to index i ; Traverse the array ; If arr [ i ] is greater than or equal to K ; Mark possible 0 ; If last + arr [ i ] is greater than K ; Increment res by 1 ; Assign arr [ i ] to last ; If possible to make the sum of pairs of adjacent elements at most K ; Otherwise prvar " - 1" ; Driver Code
function minimumInsertions ( arr , N , K ) { var possible = true ; var res = 0 ; var last = 0 ; for ( i = 0 ; i < N ; i ++ ) { if ( arr [ i ] >= K ) { possible = false ; break ; } if ( last + arr [ i ] > K ) res ++ ; last = arr [ i ] ; } if ( possible ) { document . write ( res ) ; } else { document . write ( " " ) ; } } var arr = [ 1 , 2 , 3 , 4 , 5 ] ; var K = 6 ; var N = arr . length ; minimumInsertions ( arr , N , K ) ;