Split a given array into K subarrays minimizing the difference between their maximum and minimum | Java program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Given K ; Function Call
import java . util . * ; class GFG { static int find ( int a [ ] , int n , int k ) { Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 1 ; i < n ; ++ i ) { v . add ( a [ i - 1 ] - a [ i ] ) ; } Collections . sort ( v ) ; int res = a [ n - 1 ] - a [ 0 ] ; for ( int i = 0 ; i < k - 1 ; ++ i ) { res += v . get ( i ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 8 , 15 , 16 , 23 , 42 } ; int N = arr . length ; int K = 3 ; System . out . print ( find ( arr , N , K ) + "NEW_LINE"); } }