LeetCode: 891. Sum of Subsequence Widths

LeetCode: 891. Sum of Subsequence Widths

题目描述

Given an array of integers A, consider all non-empty subsequences of A.

For any sequence S, let the width of S be the difference between the maximum and minimum element of S.

Return the sum of the widths of all subsequences of A.

As the answer may be very large, return the answer modulo 10^9 + 7.

Example 1:

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

Note:

1 <= A.length <= 20000
1 <= A[i] <= 20000

解题思路

先将原数组排序(排序并不会影响结果), 则,起始位置是 i, 结束位置是 j 的串的宽度一定是 A[j]-A[i],中间可以有串,也可以没有串。代码如下:

  for(int i = 0; i < A.size(); ++i)
  {
      for(int j = i+1; j < A.size(); ++j)
      {
         ans = (ans + (long long int)pow2[j-i-1]*(A[j]-A[i]))%1000000007;
      }
  }

复杂度 O(n^2), 会超时, 可以将中间的循环化简:

AC 代码

class Solution {
public:
    int sumSubseqWidths(vector<int>& A) {
        sort(A.begin(), A.end());
        long long int ans = 0;
        long long int pow2[20001];
        for(size_t i = 0; i <= A.size(); ++i)
        {
            if(i == 0) pow2[i] = 1;
            else pow2[i] = pow2[i-1]*2%1000000007;
        }

        for(int i = 0; i < A.size(); ++i)
        {
            ans += (pow2[i]-1)*A[i]%1000000007;
            ans = (ans - (pow2[A.size()-1-i]-1)*A[i])%1000000007;
        }

        return ans;
    }
};
全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务