返回介绍

solution / 0800-0899 / 0891.Sum of Subsequence Widths / README_EN

发布于 2024-06-17 01:03:33 字数 3130 浏览 0 评论 0 收藏 0

891. Sum of Subsequence Widths

中文文档

Description

The width of a sequence is the difference between the maximum and minimum elements in the sequence.

Given an array of integers nums, return _the sum of the widths of all the non-empty subsequences of _nums. Since the answer may be very large, return it modulo 109 + 7.

A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

 

Example 1:

Input: nums = [2,1,3]
Output: 6
Explanation: The 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.

Example 2:

Input: nums = [2]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 105

Solutions

Solution 1

class Solution:
  def sumSubseqWidths(self, nums: List[int]) -> int:
    mod = 10**9 + 7
    nums.sort()
    ans, p = 0, 1
    for i, v in enumerate(nums):
      ans = (ans + (v - nums[-i - 1]) * p) % mod
      p = (p << 1) % mod
    return ans
class Solution {
  private static final int MOD = (int) 1e9 + 7;

  public int sumSubseqWidths(int[] nums) {
    Arrays.sort(nums);
    long ans = 0, p = 1;
    int n = nums.length;
    for (int i = 0; i < n; ++i) {
      ans = (ans + (nums[i] - nums[n - i - 1]) * p + MOD) % MOD;
      p = (p << 1) % MOD;
    }
    return (int) ans;
  }
}
class Solution {
public:
  const int mod = 1e9 + 7;

  int sumSubseqWidths(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    long ans = 0, p = 1;
    int n = nums.size();
    for (int i = 0; i < n; ++i) {
      ans = (ans + (nums[i] - nums[n - i - 1]) * p + mod) % mod;
      p = (p << 1) % mod;
    }
    return ans;
  }
};
func sumSubseqWidths(nums []int) (ans int) {
  const mod int = 1e9 + 7
  sort.Ints(nums)
  p, n := 1, len(nums)
  for i, v := range nums {
    ans = (ans + (v-nums[n-i-1])*p + mod) % mod
    p = (p << 1) % mod
  }
  return
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文