Divide a sorted array in K parts with sum of difference of max and min minimized in each part | Java program to find the minimum sum of differences possible for the given array when the array is divided into K subarrays ; 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 ; Storing differences to p ; Sorting p in descending order ; Sum of the first k - 1 values of p ; Computing the result ; Driver code
import java . util . * ; class GFG { static int calculate_minimum_split ( int n , int a [ ] , int k ) { Integer [ ] p = new Integer [ n - 1 ] ; for ( int i = 1 ; i < n ; i ++ ) p [ i - 1 ] = a [ i ] - a [ i - 1 ] ; Arrays . sort ( p , new Comparator < Integer > ( ) { public int compare ( Integer a , Integer b ) { return b - a ; } } ) ; int min_sum = 0 ; for ( int i = 0 ; i < k - 1 ; i ++ ) min_sum += p [ i ] ; int res = a [ n - 1 ] - a [ 0 ] - min_sum ; return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 8 , 15 , 16 , 23 , 42 } ; int k = 3 ; int n = arr . length ; System . out . println ( calculate_minimum_split ( n , arr , k ) ) ; } }