Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit 901b187

Browse files
aQuaaQua
aQua
authored and
aQua
committed
891 finish
1 parent e02f807 commit 901b187

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

Algorithms/0891.sum-of-subsequence-widths/sum-of-subsequence-widths.go

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,26 @@ const mod = 1e9 + 7
88

99
func sumSubseqWidths(a []int) int {
1010
sort.Ints(a)
11-
res := 0
1211

1312
n := len(a)
14-
c := 1
13+
res := 0
14+
times := 1
1515
for i := 0; i < n; i++ {
16-
res = (res + a[i]*c - a[n-i-1]*c) % mod
17-
c = (c << 1) % mod
16+
res += (a[i] - a[n-i-1]) * times
17+
res %= mod
18+
times = (times << 1) % mod
1819
}
1920

20-
return res % mod
21+
return res
2122
}
23+
24+
/**
25+
* https://leetcode.com/problems/sum-of-subsequence-widths/discuss/161267/C++Java1-line-Python-Sort-and-One-Pass
26+
* For A[i]:
27+
* There are i smaller numbers,
28+
* so there are 2 ^ i sequences in which A[i] is maximum.
29+
* we should do res += A[i] * (2 ^ i)
30+
* There are n - i - 1 bigger numbers,
31+
* so there are 2 ^ (n - i - 1) sequences in which A[i] is minimum.
32+
* we should do res -= A[i] * 2 ^ (n - i - 1)
33+
*/

Algorithms/0891.sum-of-subsequence-widths/sum-of-subsequence-widths_test.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ var tcs = []struct {
1313
ans int
1414
}{
1515

16+
{
17+
[]int{1, 10001},
18+
10000,
19+
},
20+
1621
{
1722
[]int{96, 87, 191, 197, 40, 101, 108, 35, 169, 50, 168, 182, 95, 80, 144, 43, 18, 60, 174, 13, 77, 173, 38, 46, 80, 117, 13, 19, 11, 6, 13, 118, 39, 80, 171, 36, 86, 156, 165, 190, 53, 49, 160, 192, 57, 42, 97, 35, 124, 200, 84, 70, 145, 180, 54, 141, 159, 42, 66, 66, 25, 95, 24, 136, 140, 159, 71, 131, 5, 140, 115, 76, 151, 137, 63, 47, 69, 164, 60, 172, 153, 183, 6, 70, 40, 168, 133, 45, 116, 188, 20, 52, 70, 156, 44, 27, 124, 59, 42, 172},
1823
136988321,

0 commit comments

Comments
 (0)