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 thewidths of all the non-empty subsequences of _nums. Since the answer may be very large, return it modulo10^9 + 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].
Input: nums =[2,1,3]Output: 6Explanation: 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 is6.
For each number, count how many subsequences it is the maximum and how many it is the minimum. The difference gives its total contribution to the sum of widths. We sort the array and use powers of 2 to count the number of subsequences for each position.
Let nums be sorted. For each nums[i], it is the maximum in 2^i subsequences and the minimum in 2^{n-1-i} subsequences. The answer is the sum over all i of nums[i] * (2^i - 2^{n-1-i}).
#include<vector>#include<algorithm>usingnamespace std;
classSolution {
public:int sumSubseqWidths(vector<int>& nums) {
constint MOD =1e9+7;
int n = nums.size();
sort(nums.begin(), nums.end());
vector<long> pow2(n);
pow2[0] =1;
for (int i =1; i < n; ++i) pow2[i] = pow2[i-1] *2% MOD;
long res =0;
for (int i =0; i < n; ++i) {
res = (res + nums[i] * (pow2[i] - pow2[n-1-i] + MOD) % MOD) % MOD;
}
return (int)res;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.*;
classSolution {
publicintsumSubseqWidths(int[] nums) {
int MOD = 1_000_000_007, n = nums.length;
Arrays.sort(nums);
long[] pow2 =newlong[n];
pow2[0]= 1;
for (int i = 1; i < n; ++i) pow2[i]= pow2[i-1]* 2 % MOD;
long res = 0;
for (int i = 0; i < n; ++i) {
res = (res + nums[i]* (pow2[i]- pow2[n-1-i]+ MOD) % MOD) % MOD;
}
return (int)res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funsumSubseqWidths(nums: IntArray): Int {
val MOD = 1_000_000_007L
val n = nums.size
nums.sort()
val pow2 = LongArray(n)
pow2[0] = 1Lfor (i in1 until n) pow2[i] = pow2[i-1] * 2 % MOD
var res = 0Lfor (i in0 until n) {
res = (res + nums[i] * ((pow2[i] - pow2[n-1-i] + MOD) % MOD)) % MOD
}
return res.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defsumSubseqWidths(self, nums: list[int]) -> int:
MOD =10**9+7 n = len(nums)
nums.sort()
pow2 = [1] * n
for i in range(1, n):
pow2[i] = pow2[i-1] *2% MOD
res =0for i in range(n):
res = (res + nums[i] * (pow2[i] - pow2[n-1-i])) % MOD
return res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnsum_subseq_widths(mut nums: Vec<i32>) -> i32 {
constMOD: i64=1_000_000_007;
let n = nums.len();
nums.sort();
letmut pow2 =vec![1i64; n];
for i in1..n { pow2[i] = pow2[i-1] *2%MOD; }
letmut res =0i64;
for i in0..n {
res = (res + nums[i] asi64* (pow2[i] - pow2[n-1-i] +MOD) %MOD) %MOD;
}
res asi32 }
}