LeetCode 891. Sum of Subsequence Widths

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
static int N = 100010, MOD = (int) 1e9 + 7;
static long[] p = new long[N];
static {
p[0] = 1;
for (int i = 1; i < N; ++i) p[i] = p[i - 1] * 2 % MOD;
}
public int sumSubseqWidths(int[] nums) {
int n = nums.length;
long ans = 0;
Arrays.sort(nums);
for (int i = 0; i < n; ++i) {
ans += (p[i] * nums[i]) % MOD;
ans %= MOD;
ans -= (p[n - i - 1] * nums[i]) % MOD;
ans %= MOD;
}
return (int) ans;
}
}
// https://leetcode.cn/problems/sum-of-subsequence-widths/solutions/1977822/by-ac_oier-6tyk/