text: Minimize the maximum difference of adjacent elements after at most K insertions | Python3 program to find the minimum of maximum difference 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: def minMaxDiff ( arr , n , k ) : NEW_LINE INDENT max_adj_dif = float ( ' - inf ' ) ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT max_adj_dif = max ( max_adj_dif , abs ( arr [ i ] - arr [ i + 1 ] ) ) ; NEW_LINE DEDENT if ( max_adj_dif == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT best = 1 ; NEW_LINE worst = max_adj_dif ; NEW_LINE while ( best < worst ) : NEW_LINE INDENT mid = ( best + worst ) // 2 ; NEW_LINE required = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT required += ( abs ( arr [ i ] - arr [ i + 1 ] ) - 1 ) // mid NEW_LINE DEDENT if ( required > k ) : NEW_LINE INDENT best = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT worst = mid NEW_LINE DEDENT DEDENT return worst NEW_LINE DEDENT arr = [ 3 , 12 , 25 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE k = 7 NEW_LINE print ( minMaxDiff ( arr , n , k ) ) NEW_LINE