Problem Description
Given an array of integers, compute the sum of the widths of all non-empty subsequences. The width of a subsequence is defined as the difference between its maximum and minimum element. Since the answer can be very large, return it modulo 10^9 + 7.
Key Insights
- Sort the array so that the relative order makes it easier to count contributions.
- In a sorted array, each element can serve as the minimum in some subsequences and as the maximum in others.
- The number of subsequences where the element at index i is the maximum is 2^i.
- Similarly, the number where it is the minimum is 2^(n-1-i).
- The contribution of a given element is its value multiplied by (2^i - 2^(n-1-i)).
- Summing these contributions over all elements and taking mod 10^9 + 7 gives the answer.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting plus O(n) for iteration, overall O(n log n)
Space Complexity: O(n) for storing precomputed powers modulo 10^9 + 7
Solution
The solution follows these steps:
- Sort the input array.
- Precompute powers of 2 modulo 10^9 + 7 for indices from 0 to n-1.
- For each element at index i in the sorted array, calculate its contribution:
- When considered as the maximum, it appears in 2^i subsequences.
- When considered as the minimum, it appears in 2^(n-1-i) subsequences.
- Subtract the minimum contribution from the maximum contribution and aggregate the results.
- Return the final answer modulo 10^9 + 7.
Data Structures:
- Sorted array.
- Auxiliary array for precomputed powers of 2.
Algorithmic Approach:
- Sorting the array ensures that when iterating from left to right, elements before index i are always smaller, and those after are larger.
- Modular arithmetic is used throughout the solution to manage large numbers and to ensure results stay within the required limits.