Split a given array into K subarrays minimizing the difference between their maximum and minimum | Function to find the subarray ; Add the difference to vectors ; Sort vector to find minimum k ; Initialize result ; Adding first k - 1 values ; Return the minimized sum ; Given array arr ; Given K ; Function Call
function find ( a , n , k ) { var v = [ ] ; for ( i = 1 ; i < n ; ++ i ) { v . push ( a [ i - 1 ] - a [ i ] ) ; } v . sort ( ( a , b ) => a - b ) ; var res = a [ n - 1 ] - a [ 0 ] ; for ( i = 0 ; i < k - 1 ; ++ i ) { res += v [ i ] ; } return res ; } var arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] ; var N = arr . length ; var K = 3 ; document . write ( find ( arr , N , K ) + " " ) ;