We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 27ef6d5 commit 7c2e8c4Copy full SHA for 7c2e8c4
C++/sum-of-subsequence-widths.cpp
@@ -0,0 +1,18 @@
1
+// Time: O(n)
2
+// Spce: O(1)
3
+
4
+class Solution {
5
+public:
6
+ int sumSubseqWidths(vector<int>& A) {
7
+ static const int M = 1e9 + 7;
8
+ sort(A.begin(), A.end());
9
+ // sum(A[i] * (2^i - 2^(len(A)-1-i))), i = 0..len(A)-1
10
+ // <=>
11
+ // sum(((A[i] - A[len(A)-1-i]) * 2^i), i = 0..len(A)-1
12
+ int64_t result = 0l, c = 1l;
13
+ for (int i = 0; i < A.size(); ++i, c = (c << 1) % M) {
14
+ result = (result + (A[i] - A[A.size() - 1 - i]) * c % M) % M;
15
+ }
16
+ return (result + M) % M;
17
18
+};
0 commit comments