Maximum sum after rearranging the array for K queries | Function to find maximum sum after rearranging array elements ; Auxiliary array to find the count of each selected elements Initialize with 0 ; Finding count of every element to be selected ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain the count array ; Iterating over the count array to get the final array ; Variable to store the maximum sum ; Sorting both the arrays ; Loop to find the maximum sum ; Driver code
def maxSumArrangement ( A , R , N , M ) : NEW_LINE INDENT count = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l = l - 1 NEW_LINE r = r - 1 NEW_LINE count [ l ] = count [ l ] + 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT count [ r ] = count [ r ] - 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT count [ i ] = count [ i ] + count [ i - 1 ] NEW_LINE DEDENT ans = 0 NEW_LINE count . sort ( ) NEW_LINE A . sort ( ) NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT ans = ans + A [ i ] * count [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 2 , 6 , 10 , 1 , 5 , 6 ] NEW_LINE R = [ [ 1 , 3 ] , [ 4 , 6 ] , [ 3 , 4 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( R ) NEW_LINE print ( maxSumArrangement ( A , R , N , M ) ) NEW_LINE