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

Commit f80669a

Browse files
authored
2597. The Number of Beautiful Subsets (#9)
* remove-nth-node-from-end-of-list * Create the-number-of-beautiful-subsets.cs
1 parent d66d84a commit f80669a

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* time O(n)
3+
* space O(n)
4+
*/
5+
6+
public class Solution {
7+
public int BeautifulSubsets(int[] nums, int k) {
8+
Dictionary<int, int> cnt = new Dictionary<int, int>();
9+
foreach (int x in nums) {
10+
if (cnt.ContainsKey(x)) {
11+
cnt[x]++;
12+
} else {
13+
cnt[x] = 1;
14+
}
15+
}
16+
17+
Func<int, int> count = (int x) => {
18+
int y = x;
19+
while (cnt.ContainsKey(y - k)) {
20+
y -= k;
21+
}
22+
List<int> dp = new List<int> { 1, 0 };
23+
for (int i = y; i <= x; i += k) {
24+
dp = new List<int> { dp[0] + dp[1], dp[0] * ((1 << cnt[i]) - 1) };
25+
}
26+
return dp[0] + dp[1];
27+
};
28+
29+
int result = 1;
30+
foreach (var kvp in cnt) {
31+
int i = kvp.Key;
32+
if (!cnt.ContainsKey(i + k)) {
33+
result *= count(i);
34+
}
35+
}
36+
return result - 1;
37+
}
38+
}

0 commit comments

Comments
 (0)