Minimum array insertions required to make consecutive difference <= K | CPP implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minInsertions ( int H [ ] , int n , int K ) { int inser = 0 ; for ( int i = 1 ; i < n ; ++ i ) { float diff = abs ( H [ i ] - H [ i - 1 ] ) ; if ( diff <= K ) continue ; else inser += ceil ( diff / K ) - 1 ; } return inser ; } int main ( ) { int H [ ] = { 2 , 4 , 8 , 16 } , K = 3 ; int n = sizeof ( H ) / sizeof ( H [ 0 ] ) ; cout << minInsertions ( H , n , K ) ; return 0 ; }