题目:
Given the array nums
consisting of n
positive integers. You computed the sum of all non-empty continous subarrays from the array and then sort them in non-decreasing order, creating a new array of n * (n + 1) / 2
numbers.
Return the sum of the numbers from index left
to index right
(indexed from 1), inclusive, in the new array. Since the answer can be a huge number return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 5 Output: 13 Explanation: All subarray sums are 1, 3, 6, 10, 2, 5, 9, 3, 7, 4. After sorting them in non-decreasing order we have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 1 to ri = 5 is 1 + 2 + 3 + 3 + 4 = 13.
Example 2:
Input: nums = [1,2,3,4], n = 4, left = 3, right = 4 Output: 6 Explanation: The given array is the same as example 1. We have the new array [1, 2, 3, 3, 4, 5, 6, 7, 9, 10]. The sum of the numbers from index le = 3 to ri = 4 is 3 + 3 = 6.
Example 3:
Input: nums = [1,2,3,4], n = 4, left = 1, right = 10 Output: 50
Constraints:
1 <= nums.length <= 10^3
nums.length == n
1 <= nums[i] <= 100
1 <= left <= right <= n * (n + 1) / 2
算法解析:
解法一:暴力破解法
解法二:最小堆,本质和暴力差不多
代码如下
解法三: 二分搜索 + sliding window
主要是get函数,解析如下面两图
代码如下:
class Solution {
public:
typedef long long LL;
typedef pair<int,LL> pIL;
const int MOD = 1e9 + 7;
vector<LL> s, ss;
int n;
pIL get(LL mid)
{
int cnt = 0;
LL sum = 0;
for(int i = 1,j = 0; i <= n; i++)
{
while(s[i] - s[j] > mid) j++;
if(j < i){
cnt += i - j;
//sum += s[i] * (i-j) - (ss[i-1] - ss[j - 1]);
sum += s[i]*(i-j) - ss[i-1];
if(j) sum += ss[j -1];
}
}
return {cnt,sum};
}
LL fss(int m)
{
LL l = 0, r = ss.back();
while(l < r)
{
LL mid = l + r >>1;
auto t = get(mid); /* x <= mid (count,ssum) */
if(t.first >= m) r = mid;
else l = mid + 1;
}
auto t = get(r);
return t.second - (t.first - m)*r;
}
int rangeSum(vector<int>& nums, int n, int left, int right) {
this->n = n;
s.resize(n + 1);
ss.resize(n + 1);
s[0] = 0, ss[0] = 0;
for(int i = 1; i <= n; i++)
{
s[i] = s[i - 1] + nums[i - 1];
ss[i] = ss[i - 1] + s[i];
}
return (fss(right) - fss(left - 1)) % MOD;
}
};