LeetCode Solutions
891. Sum of Subsequence Widths
Time: Space:
class Solution {
public:
int sumSubseqWidths(vector<int>& nums) {
constexpr int kMod = 1'000'000'007;
const int n = nums.size();
long ans = 0;
long exp = 1;
sort(begin(nums), end(nums));
for (int i = 0; i < n; ++i, exp = exp * 2 % kMod) {
ans += (nums[i] - nums[n - i - 1]) * exp;
ans %= kMod;
}
return ans;
}
};
class Solution {
public int sumSubseqWidths(int[] nums) {
final int kMod = 1_000_000_007;
final int n = nums.length;
long ans = 0;
long exp = 1;
Arrays.sort(nums);
for (int i = 0; i < n; ++i, exp = exp * 2 % kMod) {
ans += (nums[i] - nums[n - i - 1]) * exp;
ans %= kMod;
}
return (int) ans;
}
}
class Solution:
def sumSubseqWidths(self, nums: List[int]) -> int:
kMod = 1_000_000_007
n = len(nums)
ans = 0
exp = 1
nums.sort()
for i in range(n):
ans += (nums[i] - nums[n - i - 1]) * exp
ans %= kMod
exp = exp * 2 % kMod
return ans