Skip to content

Commit 4ae22e7

Browse files
committed
891
1 parent 5ee5d6f commit 4ae22e7

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Greedy/891.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## Sum of Subsequence Widths
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/sum-of-subsequence-widths/)
6+
7+
---
8+
9+
#### Solution
10+
11+
- See Code
12+
13+
---
14+
15+
#### Code
16+
17+
> Complexity T : O(NlogN)
18+
19+
```python
20+
class Solution:
21+
'''
22+
(1) 先对原始序列排序(排序是不影响结果的哦,这个很好理解)
23+
(2)现在单独分析一个排序后的元素A[i],那么这个元素在所有子集中,有几次是被作为最大值的?又有几次是被作为最小值的?
24+
(3)继续分析,很显然A[i]被作为最大值的次数为 2^i - 1次(这里i从0开始),如何理解?0 ~ i 的所有子集共有2^(i+1)种,又因为每一位又两种状态,所以取最后一位被选中的有 2^i种,再减去只取这一位的1种,所以最后只有2^i - 1 。
25+
(4)继续分析,很显然A[i]被作为最小的次数为 2^(n - i - 1) - 1次(这里i从0开始,n为数列的长度),倒过来分析,此时的i为最低位。
26+
'''
27+
def sumSubseqWidths(self, A: List[int]) -> int:
28+
A.sort()
29+
n, res, mod = len(A), 0, 10**9 + 7
30+
pow2 = [1]
31+
for i in range(1, n): # 先把2的次方求好
32+
pow2.append(pow2[-1] * 2 % mod)
33+
34+
for i, x in enumerate(A):
35+
res += (pow2[i] - 1) * x # x 被作为最大值得 次数 应该加上
36+
res -= (pow2[n-1-i] - 1) * x # x 被作为最小值得 次数 应该减去
37+
res %= mod
38+
return res
39+
```

0 commit comments

Comments
 (0)