Description
We have an array of integers, nums, and an array of requests where requests[i] = [starti, endi]. The ith request asks for the sum of nums[starti] + nums[starti + 1] + … + nums[endi - 1] + nums[endi]. Both starti and endi are 0-indexed.
Return the maximum total sum of all requests among all permutations of nums.
Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: nums = [1,2,3,4,5], requests = [[1,3],[0,1]]
Output: 19
Explanation: One permutation of nums is [2,1,3,4,5] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 1 + 3 + 4 = 8
requests[1] -> nums[0] + nums[1] = 2 + 1 = 3
Total sum: 8 + 3 = 11.
A permutation with a higher total sum is [3,5,4,2,1] with the following result:
requests[0] -> nums[1] + nums[2] + nums[3] = 5 + 4 + 2 = 11
requests[1] -> nums[0] + nums[1] = 3 + 5 = 8
Total sum: 11 + 8 = 19, which is the best that you can do.
Example 2:
Input: nums = [1,2,3,4,5,6], requests = [[0,1]]
Output: 11
Explanation: A permutation with the max total sum is [6,5,4,3,2,1] with request sums [11].
Example 3:
Input: nums = [1,2,3,4,5,10], requests = [[0,2],[1,3],[1,1]]
Output: 47
Explanation: A permutation with the max total sum is [4,10,5,3,2,1] with request sums [19,18,10].
Constraints:
- n == nums.length
- 1 <= n <= 105
- 0 <= nums[i] <= 105
- 1 <= requests.length <= 105
- requests[i].length == 2
- 0 <= starti <= endi < n
分析
题目的意思是:给你一个数组nums,一些requests,表示的是区间,求出nums的一个排列使得根据requests表示的区间求得的和最大。
- 一个最简单的贪心方法就是统计requests表示的区间的频率,排序,然后对nums排序,然后频率越高的索引赋予nums里面的大的值。这样就能保证最大了。我用字典做了一下,然后超时了。
- 另一个方法是统计区间:首先计算数组 nums 的每个下标位置被查询的次数。维护一个差分数组,对于每个查询范围只在其开始和结束位置进行记录,例如查询范围是 [start,end],则只需要将 start 处的被查询的次数加 1,将 end+1 处的被查询的次数减 1即可(如果 end+1 超出数组下标范围则不需要进行减 1 的操作),然后对于被查询的次数的差分数组计算前缀和,即可得到数组 nums 的每个下标位置被查询的次数。使用数组 counts 记录数组 nums 的每个下标位置被查询的次数,则数组counts 和数组 nums 的长度相同。
比如:
[1,2,3,4,5]
[[1,3],[0,1]]
差分数组为:
[1, 1, -1, 0, -1]
[1, 2, 1, 1, 0]
通过差分数组就可以得到每个位置的频率了,真是不可思议,学习了。
差分数组
对于数组a[i],我们令d[i]=a[i]-a[i-1] (特殊的,第一个为d[1]=a[1]),则d[i]为一个差分数组。
我们发现统计d数组的前缀和sum数组,有
sum[i]=d[1]+d[2]+d[3]+…+d[i]=a[1]+a[2]-a[1]+a[3]-a[2]+…+a[i]-a[i-1]=a[i],即前缀和sum[i]=a[i];
因此每次在区间[l,r]增减x只需要令d[l]+x,d[r+1]-x,就可以保证[l,r]增加了x,而对[1,l-1]和[r+1,n]无影响。 复杂度则是O(n)的。
代码
class Solution:
def maxSumRangeQuery(self, nums: List[int], requests: List[List[int]]) -> int:
MOD=10**9+7
n=len(nums)
counts=[0]*n
for start,end in requests:
counts[start]+=1
if(end+1<n):
counts[end+1]-=1
# print(counts)
for i in range(1,n):
counts[i]+=counts[i-1]
# print(counts)
counts.sort()
nums.sort()
res=0
for num,count in zip(nums,counts):
res+=num*count
return res%MOD
参考文献
所有排列中的最大和差分数组