leetcode 891. Sum of Subsequence Widths

原题链接

The width of a sequence is the difference between the maximum and minimum elements in the sequence.

Given an array of integers nums, return the sum of the widths of all the non-empty subsequences of nums. Since the answer may be very large, return it modulo 109 + 7.

subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

这是道数学题,求所有子序列的最大值和最小值之差(宽度)的和

最暴力的解法就是排列组合,看看序列长度计算一下复杂度100000!,那还是歇着吧

子序列的最大值和最小值是跟序列的顺序无关,这个序列的最大值和最小值如果固定作为一组,那么中间值的个数变化并不会影响序列的宽度,将最大值和最小值一样的序列的个数乘以宽度就得到了这组的宽度和

将所有最大值和最小值组的宽度相加,就是总宽度和

最大和最小值的组数就是排序后nums[i],nums[j]之间选任意个数出来的组合,个数为2^(j-i-1)个(tms[j-i-1]),这里可以去查询排列组合的知识

因此有第一版代码:

class Solution {
public:
    int sumSubseqWidths(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        long tms[100000] = {1};
        int md = (1e9)+7,rst = 0;
        for (int i = 1; i<= nums.size(); i++) {
            tms[i] = (tms[i-1] <<1)%md;
        }
        for (int i = 0; i< nums.size(); i++) {
            for (int j = i+1; j<nums.size(); j++) {
                if(nums[i] < nums[j]) {
                    rst = (tms[j -i -1] * (nums[j] -nums[i]) + rst)%md;
                }
            }
        }
        return rst;
    }
};

所有case都能过,但是超时了。。。。

明显sort是n*log(n),需要优化的是双层嵌套循环

看双层循环的第二层,如果当前点是j-1,那么从0到j-1的所有宽度和为

sm(j-1) = tms[j-2]*(nums[j-1] - nums[0]) +.........+tms[0]*(nums[j-1] - nums[j-2)

同理

sm(j) = tms[j-1]*(nums[j] - nums[0]) +.........+tms[0]*(nums[j] - nums[j-1)

这里是为了求sm(j-1)与sm(j)的递推关系,nums[j] - nums[0]拆成

nums[j] - nums[0] = nums[j] - nums[j-1] + nums[j-1] - nums[0] 

带入sm(j)等式,将nums[j] - nums[j-1]提出来:

sm(j) = 2*(sm[j-1] + (tms[j-1] -1) * (nums[j] - nums[j-1])) + (nums[j] - nums[j-1])

这就求得了sm(j)和sm(j-1)的关系式,将sm从1🏠到length

就得出答案了,将j替换成i:

class Solution {
public:
    int sumSubseqWidths(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        long tms = 1 ,md = (1e9)+7,rst = 0,sm = 0;
        for (int i = 1; i< nums.size(); i++) {
            sm = (((tms -1) *(nums[i] - nums[i-1]) + sm)<<1)%md +nums[i] - nums[i-1];
            rst = (rst +sm) %md;
            tms = (tms <<1)%md;
        }
        return rst;
    }
};

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值