Sum of Subsequence Widths LT891
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
Idea 1. 刚开始想subset穷举, sort the array and get all the pair (0<= i < j <= n-1, A[i] < A[j]) such that (A[j] - A[i]) * 2^(j-i-1), saw an amazing online soloution, consider the contribution for each element, assume sequence is like A[0]...A[i-1]A[i]A[i+1]...A[n-1], on the left, there are i numbers < A[i], 2^(i) subsequence where A[i] is the maximu, on the right, there are n-1-i numbers > A[i], 2^(n-1-i) subsequence A[i] as minimum, hence we have
res = A[i]*2^(i) - A[i]*2^(n-1-i)
another trick to save compute 2^(n-1-i) and 2^(i) separately, sum(A[n-1-i]*2^(n-1-i)) = sum(A[n-1-i]*2^(i))
1 << i
(c=1 << 1) incrementely
Time complexity: O(nlogn)
Space complexity: O(1)
1 class Solution { 2 public int sumSubseqWidths(int[] A) { 3 long res = 0; 4 long mod = (long)1e9+7; 5 long c = 1; 6 int n = A.length; 7 8 Arrays.sort(A); 9 10 for(int i = 0; i < A.length; ++i, c = (c << 1)%mod) { 11 res = (res + (A[i] - A[n - 1 - i]) * c + mod)%mod; 12 } 13 14 return (int)(res); 15 } 16 }