leetcode: 891. Sum of Subsequence Widths

description

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



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

分析

从题意上来看,是把输入的列表元素做为 set 来用。后续从 set 中抽取任意的元素组成列表,并求出列表中元素的max 和 min 的差值。本题只需要求出大小差值,不要求保持输入原数组的有序性。

TLE 版本:

class Solution(object):
    def sumSubseqWidths(self, A):
        """
        :type A: List[int]
        :rtype: int
        """
        A, N = sorted(A), len(A)
        ssum = 0
        for i in range(0, N):
            for j in range(i+1, N):
                ssum += (A[j] - A[i]) * (1 << j-i-1) 
                ssum %= 1000000007   
        return ssum

需要修改 ssum 的增加的数学表达式
ssum += A[j] * (1<<j-i -1) for i in range(0, j-1) + others 
通过优化表达式,可以将二重循环优化为一重循环


        ssum = 0
        for i in range(0, N):
            ssum = ssum + A[i] * ((1 << i) - (1 << (N-1-i))) 
            ssum %= 1000000007
                
        return ssum
        
 Runtime: 1144 ms, faster than 45.00% of Python online submissions for Sum of Subsequence Widths.    

原文地址:https://www.cnblogs.com/tmortred/p/14381914.html