Sum of Subsequence Widths

Similar Problems:

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

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

// https://code.dennyzhang.com/sum-of-subsequence-widths // Basic Ideas: dynamic programming + hashmap // // Notice: 1 <= A[i] <= 20000 // Notice: the order doesn't matter // Notice: For each combination, only the min and max impact the result. // For each element, we know how many combination ends with it and start with it. // // Complexity: Time O(n*log(n)), Space O(1) import ("math" "sort") func sumSubseqWidths(A []int) int { mod := int(math.Pow(10, 9)+7) sort.Ints(A) res := 0 c := 1 for i, _ := range A { // how many ends with v: 2^i // how many starts with v: 2^(n-1-i) res = (res + mod+(A[i]*c)%mod-(A[len(A)-1-i]*c)%mod)%mod c = (c*2)%mod } return res }