Problem
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: Math
Sort the array, for A[i]:
- i numbers <= A[i]. A[i] is the upper bound of 2^i subsequences.
- n – i – 1 numbers >= A[i]. A[i] is the lower bound of 2^(n – i – 1) subsequences.
- A[i] contributes A[i] * 2^i – A[i] * 2^(n – i – 1) to the ans.
Time complexity: O(nlogn)
Space complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 56 ms class Solution { public: int sumSubseqWidths(vector<int>& A) { constexpr long kMod = 1e9 + 7; const int n = A.size(); sort(begin(A), end(A)); long ans = 0; long p = 1; for (int i = 0; i < n; ++i) { ans = (ans + (A[i] - A[n - i - 1]) * p) % kMod; p = (p << 1) % kMod; } return (ans + kMod) % kMod; } }; |
Time complexity: O(n)
Space complexity: O(n)
Counting sort
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Author: Huahua // Running time: 16 / 44 ms (beats 100%) static auto x = [](){std::ios::sync_with_stdio(false);cin.tie(nullptr);return nullptr;}(); class Solution { public: int sumSubseqWidths(vector<int>& A) { constexpr long kMod = 1e9 + 7; const int n = A.size(); countingSort(A); long ans = 0; long p = 1; for (int i = 0; i < n; ++i) { ans = (ans + (A[i] - A[n - i - 1]) * p) % kMod; p = (p << 1) % kMod; } return (ans + kMod) % kMod; } private: void countingSort(vector<int>& A) { int max_v = INT_MIN; int min_v = INT_MAX; for (int a : A) { if (a > max_v) max_v = a; if (a < min_v) min_v = a; } vector<int> c(max_v - min_v + 1); for (int a : A) ++c[a - min_v]; int i = 0; int j = 0; while (i < c.size()) { if (--c[i] >= 0) A[j++] = i + min_v; else ++i; } } }; |