leetcode 891 - Sum of Subsequence Widths

https://leetcode.com/problems/sum-of-subsequence-widths/solution/
https://leetcode.com/problems/sum-of-subsequence-widths/discuss/161267/C%2B%2BJava1-line-Python-Sort-and-One-Pass

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

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
40
41
42
43
44
45
46
//Time O(NlogN), Space O(N)
class Solution {
public:
int sumSubseqWidths(vector<int>& A) {
const int mod = 1e9 + 7;
int size = A.size();

vector<long> pow(size);
pow[0] = 1;

for (int i = 1; i < size; i++)
pow[i] = (pow[i-1] * 2) % mod;

sort(A.begin(), A.end());

long result = 0;

for (int i = 0; i < size; i++) {
result = (result + (pow[i] * A[i] - pow[size - i - 1] * A[i])) % mod;
}

return result;
}
};

//Time O(NlogN), Space O(1)
class Solution {
public:
int sumSubseqWidths(vector<int>& A) {
const int mod = 1e9 + 7;
int size = A.size();

sort(A.begin(), A.end());

long result = 0;
long pow = 1;

for (int i = 0; i < size; i++) {
result = (result + (A[i] * pow - A[size - i - 1] * pow)) % mod;

pow = (pow * 2) % mod;
}

return result;
}
};