Create two sets
for ( int k = 0 ; k < n ; k ++ ) { if ( k >= i && k <= j ) { curans += a [ k ] ; pq2 . add ( a [ k ] ) ; } else pq . add ( a [ k ] ) ; } Collections . sort ( pq ) ; Collections . reverse ( pq ) ; Collections . sort ( pq2 ) ; ans = Math . max ( ans , curans ) ;