Maximum possible sub | Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store elements which are part of the sub - array currently under consideration ; Create two sets ; Swap at most X elements ; Remove the minimum of the taken elements ; Add maximum of the discarded elements ; Update the answer ; Return the maximized sub - array sum ; Driver code .
function SubarraySum ( a , n , x ) { let ans = - 10000 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i ; j < n ; j ++ ) { let curans = 0 ; let pq = [ ] ; let pq2 = [ ] ; for ( let k = 0 ; k < n ; k ++ ) { if ( k >= i && k <= j ) { curans += a [ k ] ; pq2 . push ( a [ k ] ) ; } else pq . push ( a [ k ] ) ; } pq . sort ( ) ; pq . reverse ( ) ; pq2 . sort ( ) ; ans = Math . max ( ans , curans ) ; for ( let k = 1 ; k <= x ; k ++ ) { if ( pq . length == 0 pq2 . length == 0 pq2 [ 0 ] >= pq [ 0 ] ) break ; curans -= pq2 [ 0 ] ; pq2 . shift ( ) ; curans += pq [ 0 ] ; pq . shift ( ) ; ans = Math . max ( ans , curans ) ; } } } return ans ; } let a = [ 5 , - 1 , 2 , 3 , 4 , - 2 , 5 ] ; let x = 2 ; let n = a . length ; document . write ( SubarraySum ( a , n , x ) ) ;