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 print " - 1" ; Driver Code
def minimumInsertions ( arr , N , K ) : NEW_LINE INDENT possible = 1 NEW_LINE res = 0 NEW_LINE last = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= K ) : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT if ( last + arr [ i ] > K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT last = arr [ i ] NEW_LINE DEDENT if ( possible ) : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE K = 6 NEW_LINE N = len ( arr ) NEW_LINE minimumInsertions ( arr , N , K ) NEW_LINE DEDENT