Maximum sum after rearranging the array for K queries | C # program to find the 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 ; 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 readonly array ; Variable to store the maximum sum ; Sorting both the arrays ; Loop to find the maximum sum ; Driver code
using System ; class GFG { static int maxSumArrangement ( int [ ] A , int [ , ] R , int N , int M ) { int [ ] count = new int [ N ] ; int i ; for ( i = 0 ; i < M ; ++ i ) { int l = R [ i , 0 ] , r = R [ i , 1 ] + 1 ; l -- ; r -- ; count [ l ] ++ ; if ( r < N ) count [ r ] -- ; } for ( i = 1 ; i < N ; ++ i ) { count [ i ] += count [ i - 1 ] ; } int ans = 0 ; Array . Sort ( count ) ; Array . Sort ( A ) ; for ( i = N - 1 ; i >= 0 ; -- i ) { ans += A [ i ] * count [ i ] ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 6 , 10 , 1 , 5 , 6 } ; int [ , ] R = { { 1 , 3 } , { 4 , 6 } , { 3 , 4 } } ; int N = A . Length ; int M = R . GetLength ( 0 ) ; Console . Write ( maxSumArrangement ( A , R , N , M ) ) ; } }