LeetCode891 Sum of Subsequence Widths(Not fully solved)

Given an array of integers A, consider all non-empty subsequences of A.
For any sequence S, we define the width of S be the difference between the maximum and minimum element of S.(maybe we should call them range)
so we need to return the sum of width of all subsequence of A.
Do not forget to modulo 10^9+7

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.

this is a subsequence related problem, and it feels like can be done in monotonic stack idea, but how?

Intuition:
even thoufgh this problem requires “subsequence”, but acutally the order doesn;t matter when we calculate the results. will this discovery help us? let’s see.

for each number A[i]:
assume we have k numbers that is less than A[i], so there will be 2^k sequecne that use A[i] as the maximum in current sequence.
and then, we will also have n-k-1 numbers that larger than A[i], so there will be 2^(n-k-1) sequecne that use A[i] as the minimum in current sequence.
so for every sequece that contains A[i], the positive contribution of the final result on those sequences will be A[i] * 2^k, and the negative contribution of the final results on those sequence will be -A[i]*2^(n-k-1).
so how can we get the number that less than A[i] and the number that are more than A[i]? presort.

class Solution {
    public int sumSubseqWidths(int[] A) {
        Arrays.sort(A);
        long c = 1, res = 0, mod = (long)1e9 + 7;
        for (int i = 0, n = A.length; i < n; ++i, c = c * 2 % mod)
            res = (res + A[i] * c - A[n - i - 1] * c) % mod; //here, we use a different way to solve this, in stead of repeatedly calculate the math.pow(), we let c times 2 each loop, and we find the sysmteric of current i, so that means A[i] has c number of subsquence that the max is  A[i], and we have c number of subsquece which contains A[n-i-1] that the min value is A[n-i-1]
        return (int)((res + mod) % mod);
    }
}

the following is the code I write by myself, but it can’t be accepted. and I can’t understand why.

class Solution {
    public int sumSubseqWidths(int[] A) {
        Arrays.sort(A);
        int mod = 1000000007;
        
        int res = 0;
        res -= A[0] * (int)Math.pow(2, A.length - 1) % mod;
        System.out.println(res);
        for (int i = 1; i<A.length - 1; i++) {
            res = (res + A[i] * (int)Math.pow(2, i) - A[i] * (int)Math.pow(2, A.length - i - 1)) % mod;
            System.out.println(res);
        }
        res += A[A.length - 1] * (int)Math.pow(2, A.length - 1) % mod;
        System.out.println(res);
        
        return res;
    }
}

even eough this problem didn’t explicitly using monotonic Stack, but the general idea is very similiar.

posted @ 2020-05-25 06:34  EvanMeetTheWorld  阅读(15)  评论(0)    收藏  举报