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;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
06-29 17:30
找实习找着找着就要进入7月了,马上秋招也要开始了,找实习还有意义吗?
绝迹的星:有面就面, 没面上就当日薪4位数大佬免费培训, 面上了再考虑要不要实习
点赞 评论 收藏
分享
在debug的柠檬精...:好消息:现在HR挑三拣四 15年后 HR跪着求要简历 坏消息:被挑的是这代人,到时候求人的也是这代人。真好。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务