Python learning diary (1) LeetCode 1376

LetCode 1376

https://leetcode.com/problems/time-needed-to-inform-all-employees/

The problem is finding the time to inform all the employee, then the employee know if you know all the time, it is seeking max. How to calculate employee time know it, just find to his manager to head up the path, you can traverse the tree. The tree is now done through the back pointer (from the child node point to the parent), then from a child node to find the root node (head) to get this time of leaf nodes employee notified. Middle of what can be optimized if there is a parent node has been calculated this time, there is no need to continue the double-counting.

code show as below:

from typing import List

class Solution:
    def __getCost(self, pos: int, manager: List[int], informTime:List[int], cost:List[int]) -> int:
        if manager[pos] == -1:
            return informTime[pos]
        
        if cost[pos] > 0:
            return cost[pos]

        cost[pos] = self.__getCost(manager[pos], manager, informTime, cost) + informTime[pos]
        
        return cost[pos]

    def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
        if n == 0:
            return 0
        
        cost = [0]*n
        for i in range(0,n):
            self.__getCost(i, manager, informTime, cost)

        return max(cost)

sln = Solution()
assert(sln.numOfMinutes(0,0, [-1], [0]) == 0)
assert(sln.numOfMinutes(6, 2, [2, 2, -1, 2, 2, 2], [0,0, 1, 0, 0, 0]) == 1)
assert(sln.numOfMinutes(7, 6, [1, 2, 3, 4, 5, 6, -1], [0, 6, 5, 4, 3, 2, 1]) == 21)
assert(sln.numOfMinutes(15, 0, [-1,0,0,1,1,2,2,3,3,4,4,5,5,6,6], [1,1,1,1,1,1,1,0,0,0,0,0,0,0,0]) == 3)

More interesting here is that the first time I write a python on leetcode. Found List [int] this type is not mentioned in the book, I could not tell when running this type. Google only to find the original is in the library inside https://docs.python.org/3/library/typing.html , some type hint, to help better understand the code.

Published an original article · won praise 0 · Views 6

Guess you like

Origin blog.csdn.net/frankguodongchen/article/details/104816472