版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013596119/article/details/81979606
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
Answer:
[1,2,3,4,5]
最大值的组合数量为
5: 2^4-1=15
4: 2^3-1=7
3: 2^2-1=3
2: 2^1-1=1
最小值的组合数量为
1: 2^4-1=15
2: 2^3-1=7
3: 2^2-1=3
4: 2^1-1=1
两组之间的差值为2,4,8=>2^1,2^2,2^3
class Solution(object):
def sumSubseqWidths(self, A):
"""
:type A: List[int]
:rtype: int
"""
A=sorted(A)
len_A=len(A)
result=0
p=0
p1=1
for i in range(1,len_A):
p+=p1
p1<<=1
result+=(A[i]-A[len_A-1-i])*p
return result%(1000000007)