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 ; Driver Code ; Given array ; Given size ; Queries ; Number of queries ; Function Call
def maxSum ( n , a , l , q ) : NEW_LINE INDENT v = [ ] NEW_LINE d = [ 0 ] * n NEW_LINE for i in range ( q ) : NEW_LINE INDENT for x in range ( l [ i ] [ 0 ] , l [ i ] [ 1 ] + 1 ) : NEW_LINE INDENT if ( d [ x ] == 0 ) : NEW_LINE INDENT d [ x ] = 1 NEW_LINE DEDENT DEDENT DEDENT st = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( d [ i ] == 0 ) : NEW_LINE INDENT v . append ( a [ i ] ) NEW_LINE st . add ( i ) NEW_LINE DEDENT DEDENT v . sort ( reverse = True ) NEW_LINE c = 0 NEW_LINE for it in st : NEW_LINE INDENT a [ it ] = v NEW_LINE c += 1 NEW_LINE DEDENT pref_sum = 0 NEW_LINE temp_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp_sum += a [ i ] NEW_LINE pref_sum += temp_sum NEW_LINE DEDENT return pref_sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 8 , 4 , - 2 , - 6 , 4 , 7 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE q = [ [ 0 , 0 ] , [ 4 , 5 ] ] NEW_LINE queries = len ( q ) NEW_LINE print ( maxSum ( N , arr , q , queries ) ) NEW_LINE DEDENT