Skip to content

891. Sum of Subsequence Widths 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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;

    ranges::sort(nums);

    for (int i = 0; i < n; ++i, exp = exp * 2 % kMod) {
      ans += (nums[i] - nums[n - 1 - i]) * exp;
      ans %= kMod;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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 - 1 - i]) * exp;
      ans %= kMod;
    }

    return (int) ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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 - 1 - i]) * exp
      ans %= kMod
      exp = exp * 2 % kMod

    return ans