Rearrange array elements excluded by given ranges to maximize sum of subarrays starting from the first index | Function that finds the maximum sum all subarrays from the starting index after rearranging the array ; Stores elements after rearranging ; Keeps track of visited elements ; Traverse the queries ; Mark elements that are not allowed to rearranged ; Stores the indices ; Get indices and elements that are allowed to rearranged ; Store the current index and element ; Sort vector v in descending order ; Insert elements in array ; Stores the resultant sum ; Stores the prefix sums ; Traverse the given array ; Return the maximum sum ; Given array ; Given size ; Queries ; Number of queries ; Function Call
function maxSum ( n , a , l , q ) { let v = [ ] ; let d = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { d [ i ] = 0 ; } for ( let i = 0 ; i < q ; i ++ ) { for ( let x = l [ i ] [ 0 ] ; x <= l [ i ] [ 1 ] ; x ++ ) { if ( d [ x ] == 0 ) { d [ x ] = 1 ; } } } let st = new Set ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( d [ i ] == 0 ) { v . push ( a [ i ] ) ; st . add ( i ) ; } } v . sort ( function ( a , b ) { return b - a ; } ) ; let c = 0 ; for ( let it of st . values ( ) ) { a [ it ] = v ; c ++ ; } let pref_sum = 0 ; let temp_sum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { temp_sum += a [ i ] ; pref_sum += temp_sum ; } return pref_sum ; } let arr = [ - 8 , 4 , - 2 , - 6 , 4 , 7 , 1 ] ; let N = arr . length ; let q = [ [ 0 , 0 ] , [ 4 , 5 ] ] ; let queries = q . length ; document . write ( maxSum ( N , arr , q , queries ) ) ;