Maximum possible sub | C # implementation of the approach ; 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 .
using System ; using System . Collections . Generic ; class GFG { static int SubarraySum ( int [ ] a , int n , int x ) { int ans = - 10000 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int curans = 0 ; List < int > pq = new List < int > ( ) ; List < int > pq2 = new List < int > ( ) ; for ( int k = 0 ; k < n ; k ++ ) { if ( k >= i && k <= j ) { curans += a [ k ] ; pq2 . Add ( a [ k ] ) ; } else pq . Add ( a [ k ] ) ; } pq . Sort ( ) ; pq . Reverse ( ) ; pq2 . Sort ( ) ; ans = Math . Max ( ans , curans ) ; for ( int k = 1 ; k <= x ; k ++ ) { if ( pq . Count == 0 pq2 . Count == 0 pq2 [ 0 ] >= pq [ 0 ] ) break ; curans -= pq2 [ 0 ] ; pq2 . RemoveAt ( 0 ) ; curans += pq [ 0 ] ; pq . RemoveAt ( 0 ) ; ans = Math . Max ( ans , curans ) ; } } } return ans ; } static void Main ( ) { int [ ] a = { 5 , - 1 , 2 , 3 , 4 , - 2 , 5 } ; int x = 2 ; int n = a . Length ; Console . WriteLine ( SubarraySum ( a , n , x ) ) ; } }