#2151
Maximum Good People Based on Statements
HardArrayBacktrackingBit ManipulationEnumerationBit ManipulationEnumeration
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
We can optimize the brute-force approach by using bit manipulation to efficiently check the validity of each configuration. This allows us to quickly determine if a certain configuration of good and bad people is valid without checking every statement repeatedly.
⚙️
Algorithm
3 steps- 1Step 1: Use a bitmask to represent each person's status (good or bad).
- 2Step 2: For each bitmask, validate the statements based on the current assignment of good and bad people.
- 3Step 3: Count the number of good people in valid configurations and keep track of the maximum.
solution.py17 lines
1def maxGoodPeople(statements):
2 n = len(statements)
3 max_good = 0
4 for mask in range(1 << n):
5 valid = True
6 good_count = 0
7 for i in range(n):
8 if mask & (1 << i):
9 good_count += 1
10 for j in range(n):
11 if statements[i][j] == 1 and not (mask & (1 << j)):
12 valid = False
13 if statements[i][j] == 0 and (mask & (1 << j)):
14 valid = False
15 if valid:
16 max_good = max(max_good, good_count)
17 return max_goodℹ
Complexity note: The time complexity remains O(n²) due to the need to check n statements for each of the 2^n configurations, but we efficiently manage the checks using bit manipulation.
- 1Understanding the implications of statements is crucial for determining the validity of configurations.
- 2Bit manipulation allows for efficient representation and checking of configurations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.