Perform K of Q queries to maximize the sum of the array elements | Function to perform K queries out of Q to maximize the final sum ; Get the initial sum of the array ; Stores the contriution of every query ; Sort the contribution of queries in descending order ; Get the K most contributions ; Driver code
const getFinalSum = ( a , n , queries , q , k ) => { let answer = 0 ; for ( let i = 0 ; i < n ; i ++ ) answer += a [ i ] ; let contribution = [ ] ; for ( let i = 0 ; i < q ; i ++ ) { contribution . push ( queries [ i ] [ 1 ] - queries [ i ] [ 0 ] + 1 ) ; } contribution . sort ( ( a , b ) => b - a ) ; let i = 0 ; while ( i < k ) { answer += contribution [ i ] ; i ++ ; } return answer ; } const a = [ 1 , 1 , 2 , 2 , 2 , 3 ] ; const n = a . length ; const queries = [ [ 0 , 4 ] , [ 1 , 2 ] , [ 2 , 5 ] , [ 2 , 3 ] , [ 2 , 4 ] ] ; const q = queries . length ; let k = 3 ; document . write ( getFinalSum ( a , n , queries , q , k ) ) ;