天天看點

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

The order in initial arrays doesn't matter,

my first intuition is to sort the array.

For 

A[i]

:

There are 

i

 smaller numbers,

so there are 

2 ^ i

 sequences in which 

A[i]

 is maximum.

we should do 

res += A[i] * (2 ^ i)

There are 

n - i - 1

 bigger numbers,

so there are 

2 ^ (n - i - 1)

 sequences in which 

A[i]

 is minimum.

we should do 

res -= A[i] * 2 ^ (n - i - 1)

Done.

Time Complexity:

O(NlogN)

class Solution:
    def sumSubseqWidths(self, a):
        """
        :type A: List[int]
        :rtype: int
        """
        res=0
        a.sort()
        n=len(a)
        tmp=[1]*n
        for i in range(1,n): tmp[i]=tmp[i-1]*2
        for i in range(n):
            res+=a[i]*tmp[i]
            res-=a[i]*tmp[n-i-1]
        return res%(10**9 + 7)
    
s=Solution()
print(s.sumSubseqWidths([2,1,3]))