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 leto K subarrays ; Array to store the differences between two adjacent elements ; Iterating through the array ; Storing differences to p ; Sorting p in descending order ; Sum of the first k - 1 values of p ; Computing the result ; Driver Code
function calculate_minimum_split ( n , a , k ) { let p = Array . from ( { length : n - 1 } , ( _ , i ) => 0 ) ; for ( let i = 1 ; i < n ; i ++ ) p [ i - 1 ] = a [ i ] - a [ i - 1 ] ; p . sort ( ( a , b ) => a - b ) ; p . reverse ( ) ; let min_sum = 0 ; for ( let i = 0 ; i < k - 1 ; i ++ ) min_sum += p [ i ] ; let res = a [ n - 1 ] - a [ 0 ] - min_sum ; return res ; } let arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] ; let k = 3 ; let n = arr . length ; document . write ( calculate_minimum_split ( n , arr , k ) ) ;