Divide a sorted array in K parts with sum of difference of max and min minimized in each part | Function to find the minimum sum of differences possible for the given array when the array is divided into K subarrays ; Array to store the differences between two adjacent elements ; Iterating through the array ; Appending differences to p ; Sorting p in descending order ; Sum of the first k - 1 values of p ; Computing the result ;
def calculate_minimum_split ( a , k ) : NEW_LINE INDENT p = [ ] NEW_LINE n = len ( a ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT p . append ( a [ i ] - a [ i - 1 ] ) NEW_LINE DEDENT p . sort ( reverse = True ) NEW_LINE min_sum = sum ( p [ : k - 1 ] ) NEW_LINE res = a [ n - 1 ] - a [ 0 ] - min_sum NEW_LINE return res NEW_LINE DEDENT / * Driver code * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] NEW_LINE K = 3 NEW_LINE print ( calculate_minimum_split ( arr , K ) ) NEW_LINE DEDENT