Interview Questions/Coding/Maximum Weighted Request Sum

Maximum Weighted Request Sum

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Maximum Weighted Request Sum

A campaign analytics team owns a list of reward values and receives many interval requests. A request for l to r contributes the values currently placed at positions l through r to the campaign score. Before the campaign is finalized, the team may rearrange the reward values in any order. For each batch, determine the largest total score possible across all requests. The request intervals are fixed, but the values can be permuted. The answer is the maximum sum of all requested positions after choosing the best arrangement. Input Format: The first line contains t. Each case starts with n and q, followed by n reward values. Each of the next q lines contains l and r for a 1-indexed inclusive request interval. Output Format: For each case, print the maximum possible total score.

Examples

Example 1
Input:
1
5 3
5 3 2 4 1
1 3
2 5
4 5
Output:
29

Explanation: The five positions are requested different numbers of times. The best arrangement places larger reward values on the positions touched by more requests, producing the printed total.

Approach hint

Only the number of times each position is requested matters.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

solution.cpp