Last active
October 14, 2023 01:33
-
-
Save alvinlau/6691fb72e20843dfd0d7f72441f3d6d0 to your computer and use it in GitHub Desktop.
690. Employee Importance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # https://leetcode.com/problems/employee-importance/ | |
| # 690. Employee Importance | |
| # You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. | |
| # You are given an array of employees employees where: | |
| # employees[i].id is the ID of the ith employee. | |
| # employees[i].importance is the importance value of the ith employee. | |
| # employees[i].subordinates is a list of the IDs of the direct subordinates of the ith employee. | |
| # Given an integer id that represents an employee's ID, return the total importance value of this employee and all their direct and indirect subordinates. | |
| # Example 1: | |
| # Input: employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1 | |
| # Output: 11 | |
| # Explanation: Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3. | |
| # They both have an importance value of 3. | |
| # Thus, the total importance value of employee 1 is 5 + 3 + 3 = 11. | |
| # Example 2: | |
| # Input: employees = [[1,2,[5]],[5,-3,[]]], id = 5 | |
| # Output: -3 | |
| # Explanation: Employee 5 has an importance value of -3 and has no direct subordinates. | |
| # Thus, the total importance value of employee 5 is -3. | |
| # Constraints: | |
| # 1 <= employees.length <= 2000 | |
| # 1 <= employees[i].id <= 2000 | |
| # All employees[i].id are unique. | |
| # -100 <= employees[i].importance <= 100 | |
| # One employee has at most one direct leader and may have several subordinates. | |
| # The IDs in employees[i].subordinates are valid IDs. | |
| =begin | |
| # Definition for Employee. | |
| class Employee | |
| attr_accessor :id, :importance, :subordinates | |
| def initialize( id, importance, subordinates) | |
| @id = id | |
| @importance = importance | |
| @subordinates = subordinates | |
| end | |
| end | |
| =end | |
| # @param {Employee} employees | |
| # @param {Integer} id | |
| # @return {Integer} | |
| def get_importance(employees, id) | |
| lookup_by_id = [] | |
| employees.each{|emp| lookup_by_id[emp.id] = emp} | |
| agg_importance(lookup_by_id, id) | |
| end | |
| def agg_importance(lookup, id) | |
| emp = lookup[id] | |
| emp.importance + emp.subordinates.sum{|sub_id| agg_importance(lookup, sub_id)} | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment