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 ; Driver code ; Length of array ; Given K ; Function Call
def find ( a , n , k ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT v . append ( a [ i - 1 ] - a [ i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE res = a [ n - 1 ] - a [ 0 ] NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT res += v [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 15 , 16 , 23 , 42 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( find ( arr , N , K ) ) NEW_LINE