Problem Description
We have an array of integers, nums, and an array of requests where each request is given by [start, end]. The request asks for the sum of nums from index start to index end (inclusive). Our goal is to maximize the total sum of the results from all requests by permuting nums optimally. Since the result can be very large, return the answer modulo 10^9 + 7.
Key Insights
- Use a difference array to efficiently compute how many requests include each index.
- Apply a prefix sum on the difference array to obtain the frequency (weight) for each index.
- Sorting both nums and the frequency array helps to pair larger numbers with higher frequencies—this greedy strategy maximizes the overall sum.
- Calculate the total as the dot product of the sorted lists, applying modulo arithmetic.
Space and Time Complexity
Time Complexity: O(n log n + r) where n is the length of nums and r is the number of requests.
Space Complexity: O(n) for the frequency array.
Solution
We start by initializing a frequency array of length n+1 with zeros. For each request [start, end], we use the difference array technique: increment frequency[start] and, if applicable, decrement frequency[end+1]. We then compute the prefix sum over the frequency array to determine the count of requests that include each index. By sorting both the frequency array (ignoring the extra element after prefix summing) and the nums array, we can pair the largest numbers with the most requested positions. The final answer is computed as the sum of the products of the corresponding elements from these sorted arrays, modulo 10^9+7.