Similar Problems

Similar Problems not available

Maximum Good People Based On Statements - Leetcode Solution

Companies:

LeetCode:  Maximum Good People Based On Statements Leetcode Solution

Difficulty: Hard

Topics: backtracking bit-manipulation array  

The problem Maximum Good People Based On Statements on Leetcode can be solved using logical deductions. The problem statement is as follows:

There are n people numbered from 0 to n-1 and n statements numbered from 0 to n-1. Each person knows exactly n statements. The ith statement is true if and only if statement[i][j] is true, where 0 <= j < n.

You're given a boolean array called is_known. is_known[i] is true if and only if the ith person knows the statement 0.

Return the maximum number of good people you can invite, where a good person is a person who knows every statement.

Let's break down the problem into smaller sub-problems:

  1. Identify the people who know statement 0
  2. For each person identified in step 1, identify the statements they know based on their knowledge of statement 0
  3. Identify the people who know all the statements identified in step 2
  4. Return the count of people identified in step 3

Let's implement the steps in code:

def maximum_good_people(is_known, statements):
    # Step 1
    statement_0_knowers = set()
    for person, knowledge in enumerate(statements):
        if knowledge[0]:
            statement_0_knowers.add(person)

    # Step 2
    known_statements = [set() for _ in range(len(statements))]
    for person in statement_0_knowers:
        for statement, knowledge in enumerate(statements[person]):
            if knowledge:
                known_statements[statement].add(person)

    # Step 3
    good_people = set()
    for person in statement_0_knowers:
        if all(person in known_statements[statement] for statement in range(len(statements))):
            good_people.add(person)

    # Step 4
    return len(good_people)

Let's test the function:

>>> is_known = [True, False, True, True, False]
>>> statements = [[True, False, False, True, True],
...              [False, True, True, True, True],
...              [True, False, True, False, False],
...              [True, False, False, True, True],
...              [True, True, False, True, True]]
>>> maximum_good_people(is_known, statements)
1

In the example above, only person 0 knows statement 0. Based on their knowledge, we can identify that statements 0 and 3 are true. Person 0 also knows statements 2 and 4, but statement 2 is false. Hence, person 0 is the only good person and the function returns 1.

Maximum Good People Based On Statements Solution Code

1