Split a given array into K subarrays minimizing the difference between their maximum and minimum | C # 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
using System ; using System . Collections . Generic ; class GFG { static int find ( int [ ] a , int n , int k ) { List < int > v = new List < int > ( ) ; for ( int i = 1 ; i < n ; ++ i ) { v . Add ( a [ i - 1 ] - a [ i ] ) ; } v . Sort ( ) ; int res = a [ n - 1 ] - a [ 0 ] ; for ( int i = 0 ; i < k - 1 ; ++ i ) { res += v [ i ] ; } return res ; } public static void Main ( String [ ] args ) { int [ ] arr = { 4 , 8 , 15 , 16 , 23 , 42 } ; int N = arr . Length ; int K = 3 ; Console . Write ( find ( arr , N , K ) + " STRNEWLINE " ) ; } }