leetcode 891. Sum of Subsequence Widths

Given an array of integers A, consider all non-empty subsequences of A.

For any sequence S, let the width of S be the difference between the maximum and minimum element of S.

Return the sum of the widths of all subsequences of A. 

As the answer may be very large, return the answer modulo 10^9 + 7.

 

Example 1:

Input: [2,1,3]
Output: 6
Explanation:
Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3].
The corresponding widths are 0, 0, 0, 1, 1, 2, 2.
The sum of these widths is 6.

 

Note:

  • 1 <= A.length <= 20000
  • 1 <= A[i] <= 20000

解题思路:

先将向量排序,当A[i]时,对于j < i , 则A[i] 则和 A[j]则是子序列中的最大值和最小值,可以组成的子序列的个数为2^(i - j - 1) ;

但是这样的时间复杂度为O(n^2),会超时,则需要进行优化;

公式的话之后再推吧。

class Solution {
public:
    int sumSubseqWidths(vector<int>& A) 
    {
        if(A.empty()) return 0 ;
        int n = A.size() ;
        int res1 = 0 , res2 = 0 , modl = 1000000007 ; 
        
        sort(A.begin() , A.end()) ;
        int sum = 0 , base = 1 ; 
        for(int i = 1 ; i < n ; ++i)
        {
            sum = (sum + base) % modl ;
            res1 = (res1 + ((long)sum * (long)A[i]) % modl) % modl ;
            base = (base * 2) % modl ;
        }
        
        sum = 0 ;
        base = 1 ;
        for(int i = n - 2 ; i >= 0 ; --i)
        {
            sum = (sum + base) % modl ;
            res2 = (res2 + ((long)sum *(long) A[i]) % modl ) % modl ;
            base = (base * 2) % modl ;
        }
        
        return (res1 - res2 + modl) % modl ;
    }
};

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值