给定一个整数数组 A ,考虑 A 的所有非空子序列。
对于任意序列 S ,设 S 的宽度是 S 的最大元素和最小元素的差。
返回 A 的所有子序列的宽度之和。
由于答案可能非常大,请返回答案模 10^9+7。
示例:
输入:[2,1,3]
输出:6
解释:
子序列为 [1],[2],[3],[2,1],[2,3],[1,3],[2,1,3] 。
相应的宽度是 0,0,0,1,1,2,2 。
这些宽度之和是 6 。
提示:
1 <= A.length <= 20000
1 <= A[i] <= 20000
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/sum-of-subsequence-widths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
类似题目:
class Solution {
public:
int sumSubseqWidths(vector<int> &A) {
long long ans = 0, mod = 1e9+7;
long long n = A.size();
sort(A.begin(), A.end());
// 每个数作为最小值的时候,右侧有多少种方案 2^(n-i-1);
// 每个数作为最大值的时候,左侧有多少种方案 2^(i);
vector<long long> p2(n);
p2[0] = 1;
for(int i = 1; i < n; i++)
p2[i] = (p2[i-1]<<1)%mod;
for(int i = 0; i < n; ++i)
{
ans = (ans + (p2[i]-p2[n-i-1])*A[i])%mod;
}
return (ans+mod)%mod;
}
};
68 ms 26.6 MB C++
我的CSDN博客地址 https://michael.blog.csdn.net/
长按或扫码关注我的公众号(Michael阿明),一起加油、一起学习进步!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有