Skip to content

891. Sum of Subsequence Widths

  • Time:
  • Space:
 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 = 1e9 + 7;
    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;
  }
};
 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 = (int) 1e9 + 7;
    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;
  }
}
 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 = int(1e9) + 7
    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