Minimum array insertions required to make consecutive difference <= K | Python3 implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code
import math NEW_LINE def minInsertions ( H , n , K ) : NEW_LINE INDENT inser = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT diff = abs ( H [ i ] - H [ i - 1 ] ) ; NEW_LINE if ( diff <= K ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT inser += math . ceil ( diff / K ) - 1 ; NEW_LINE DEDENT DEDENT return inser ; NEW_LINE DEDENT H = [ 2 , 4 , 8 , 16 ] ; NEW_LINE K = 3 ; NEW_LINE n = len ( H ) ; NEW_LINE print ( minInsertions ( H , n , K ) ) ; NEW_LINE