Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/891.html

891. Sum of Subsequence Widths

Level

Hard

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 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

Solution

First sort the array A, which won’t affect the result. Then the sum of subsequence widths is the sum over 2 ^ (j - i - 1) * (A[j] - A[i]) for all pairs (i, j) such that 0 <= i < j < A.length. The result is the sum over (2 ^ i - 2 ^ (A.length - i - 1)) * A[i] for all i from 0 to A.length - 1.

  • class Solution {
        public int sumSubseqWidths(int[] A) {
            final int MODULO = 1000000007;
            Arrays.sort(A);
            int length = A.length;
            long[] pow2 = new long[length];
            pow2[0] = 1;
            for (int i = 1; i < length; i++)
                pow2[i] = pow2[i - 1] * 2 % MODULO;
            long sum = 0;
            for (int i = 0; i < length; i++)
                sum = (sum + (pow2[i] - pow2[length - 1 - i]) * A[i]) % MODULO;
            return (int) sum;
        }
    }
    
  • class Solution:
        def sumSubseqWidths(self, nums: List[int]) -> int:
            mod = 10**9 + 7
            nums.sort()
            ans, p = 0, 1
            for i, v in enumerate(nums):
                ans = (ans + (v - nums[-i - 1]) * p) % mod
                p = (p << 1) % mod
            return ans
    
    
    
  • class Solution {
    public:
        const int mod = 1e9 + 7;
    
        int sumSubseqWidths(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            long ans = 0, p = 1;
            int n = nums.size();
            for (int i = 0; i < n; ++i) {
                ans = (ans + (nums[i] - nums[n - i - 1]) * p + mod) % mod;
                p = (p << 1) % mod;
            }
            return ans;
        }
    };
    
  • func sumSubseqWidths(nums []int) (ans int) {
    	const mod int = 1e9 + 7
    	sort.Ints(nums)
    	p, n := 1, len(nums)
    	for i, v := range nums {
    		ans = (ans + (v-nums[n-i-1])*p + mod) % mod
    		p = (p << 1) % mod
    	}
    	return
    }
    

All Problems

All Solutions