text: Minimize the maximum difference of adjacent elements after at most K insertions | javascript Program to find the minimum of maximum differerence between adjacent elements after at most K insertions ; Calculate the maximum adjacent difference ; If the maximum adjacent difference is already zero ; best and worst specifies range of the maximum adjacent difference ; To store the no of insertions required for respective values of mid ; If the number of insertions required exceeds K ; Otherwise ; Driver code
code: function minMaxDiff ( arr , n , k ) { var max_adj_dif = - 1000000000 ; for ( var i = 0 ; i < n - 1 ; i ++ ) max_adj_dif = Math . max ( max_adj_dif , Math . abs ( arr [ i ] - arr [ i + 1 ] ) ) ; if ( max_adj_dif == 0 ) return 0 ; var best = 1 ; var worst = max_adj_dif ; var mid , required ; while ( best < worst ) { mid = ( best + worst ) / 2 ; required = 0 ; for ( var i = 0 ; i < n - 1 ; i ++ ) { required += parseInt ( ( Math . abs ( arr [ i ] - arr [ i + 1 ] ) - 1 ) / mid ) ; } if ( required > k ) best = mid + 1 ; else worst = mid ; } return worst ; } var arr = [ 3 , 12 , 25 , 50 ] ; var n = arr . length ; var k = 7 ; document . write ( minMaxDiff ( arr , n , k ) ) ;