|
| 1 | +/** |
| 2 | + * 2151. Maximum Good People Based on Statements |
| 3 | + * https://leetcode.com/problems/maximum-good-people-based-on-statements/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There are two types of persons: |
| 7 | + * - The good person: The person who always tells the truth. |
| 8 | + * - The bad person: The person who might tell the truth and might lie. |
| 9 | + * |
| 10 | + * You are given a 0-indexed 2D integer array statements of size n x n that represents the |
| 11 | + * statements made by n people about each other. More specifically, statements[i][j] could |
| 12 | + * be one of the following: |
| 13 | + * - 0 which represents a statement made by person i that person j is a bad person. |
| 14 | + * - 1 which represents a statement made by person i that person j is a good person. |
| 15 | + * - 2 represents that no statement is made by person i about person j. |
| 16 | + * |
| 17 | + * Additionally, no person ever makes a statement about themselves. Formally, we have that |
| 18 | + * statements[i][i] = 2 for all 0 <= i < n. |
| 19 | + * |
| 20 | + * Return the maximum number of people who can be good based on the statements made by the |
| 21 | + * n people. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number[][]} statements |
| 26 | + * @return {number} |
| 27 | + */ |
| 28 | +var maximumGood = function(statements) { |
| 29 | + const n = statements.length; |
| 30 | + let result = 0; |
| 31 | + |
| 32 | + backtrack(0, new Array(n).fill(false), 0); |
| 33 | + return result; |
| 34 | + |
| 35 | + function isValid(goodPeople) { |
| 36 | + for (let i = 0; i < n; i++) { |
| 37 | + if (!goodPeople[i]) continue; |
| 38 | + for (let j = 0; j < n; j++) { |
| 39 | + if (statements[i][j] === 0 && goodPeople[j]) return false; |
| 40 | + if (statements[i][j] === 1 && !goodPeople[j]) return false; |
| 41 | + } |
| 42 | + } |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + function backtrack(index, goodPeople, goodCount) { |
| 47 | + if (index === n) { |
| 48 | + if (isValid(goodPeople)) { |
| 49 | + result = Math.max(result, goodCount); |
| 50 | + } |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + goodPeople[index] = true; |
| 55 | + backtrack(index + 1, goodPeople, goodCount + 1); |
| 56 | + goodPeople[index] = false; |
| 57 | + backtrack(index + 1, goodPeople, goodCount); |
| 58 | + } |
| 59 | +}; |
0 commit comments