leetcode1508 Range Sum of Sorted Subarray Sums

161 篇文章 0 订阅

题目:

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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值