Partition into two subarrays of lengths k and ( N | Function to calculate max_difference ; Sum of the array ; Sort the array in descending order ; Calculating max_difference ; Driver code
function maxDifference ( arr , N , k ) { let M , S = 0 , S1 = 0 , max_difference = 0 ; for ( let i = 0 ; i < N ; i ++ ) S += arr [ i ] ; let temp ; for ( let i = 0 ; i < N ; i ++ ) { for ( let j = i + 1 ; j < N ; j ++ ) { if ( arr [ i ] < arr [ j ] ) { temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; } } } M = Math . max ( k , N - k ) ; for ( let i = 0 ; i < M ; i ++ ) S1 += arr [ i ] ; max_difference = S1 - ( S - S1 ) ; return max_difference ; } let arr = [ 8 , 4 , 5 , 2 , 10 ] ; let N = arr . length ; let k = 2 ; document . write ( maxDifference ( arr , N , k ) ) ;