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