Skip to content
This repository was archived by the owner on Sep 8, 2025. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions C#/the-number-of-beautiful-subsets.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* time O(n)
* space O(n)
*/

public class Solution {
public int BeautifulSubsets(int[] nums, int k) {
Dictionary<int, int> cnt = new Dictionary<int, int>();
foreach (int x in nums) {
if (cnt.ContainsKey(x)) {
cnt[x]++;
} else {
cnt[x] = 1;
}
}

Func<int, int> count = (int x) => {
int y = x;
while (cnt.ContainsKey(y - k)) {
y -= k;
}
List<int> dp = new List<int> { 1, 0 };
for (int i = y; i <= x; i += k) {
dp = new List<int> { dp[0] + dp[1], dp[0] * ((1 << cnt[i]) - 1) };
}
return dp[0] + dp[1];
};

int result = 1;
foreach (var kvp in cnt) {
int i = kvp.Key;
if (!cnt.ContainsKey(i + k)) {
result *= count(i);
}
}
return result - 1;
}
}