所有排列中的最大和
难度:
标签:
题目描述
代码结果
运行时间: 148 ms, 内存: 43.0 MB
/*
* 思路:
* 1. 对于每个请求区间,记录每个索引被请求的频率。
* 2. 通过计算每个索引的请求次数,确定索引的权重。
* 3. 将数组和权重排序,权重越大对应的数组值应越大。
* 4. 将排序后的数组和权重一一对应相乘,得到最大查询和。
* 5. 将结果对10^9 + 7取余后返回。
*/
import java.util.*;
import java.util.stream.*;
public class Solution {
public int maxSumRangeQuery(int[] nums, int[][] requests) {
int n = nums.length;
int mod = 1000000007;
int[] freq = new int[n];
// 记录每个索引被请求的频率
for (int[] req : requests) {
freq[req[0]]++;
if (req[1] + 1 < n) freq[req[1] + 1]--;
}
// 前缀和计算实际频率
for (int i = 1; i < n; i++) {
freq[i] += freq[i - 1];
}
// 排序
Arrays.sort(nums);
freq = Arrays.stream(freq).sorted().toArray();
// 计算结果
long result = 0;
for (int i = 0; i < n; i++) {
result = (result + (long) nums[i] * freq[i]) % mod;
}
return (int) result;
}
}
解释
方法:
The solution utilizes a difference array to efficiently calculate the frequency of each index being accessed across all requests. First, it iterates through each request and updates the difference array to track the start and end+1 of each range. Then, by taking the prefix sum of this difference array, we get the number of times each index is accessed. After sorting this 'times' array and the 'nums' array in descending order, the product of corresponding elements from both arrays (the highest numbers with the highest frequencies) maximizes the sum. The result is then taken modulo 109 + 7.
时间复杂度:
O(n log n + m)
空间复杂度:
O(n)
代码细节讲解
🦆
在解决方案中使用差分数组的原因是什么?它如何帮助处理多个请求的索引频率?
▷🦆
为什么在得到差分数组后要使用`accumulate`函数来计算每个索引被访问的次数?
▷🦆
排序`nums`和`times`数组时选择降序的理由是什么?如何保证这种方法可以得到最大的查询和?
▷🦆
你的解决方案中提到了将结果对`10^9 + 7`取余,这样做的目的是什么?
▷