MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / find_longest_chain

Function find_longest_chain

project_euler/problem_095/sol1.py:107–131  ·  view source on GitHub ↗

Finds the smallest element of longest chain >>> find_longest_chain(chain=[0, 0, 0, 0, 0, 0, 6], max_num=6) 6

(chain: list[int], max_num: int)

Source from the content-addressed store, hash-verified

105
106
107def find_longest_chain(chain: list[int], max_num: int) -> int:
108 """
109 Finds the smallest element of longest chain
110
111 >>> find_longest_chain(chain=[0, 0, 0, 0, 0, 0, 6], max_num=6)
112 6
113 """
114
115 max_len = 0
116 min_elem = 0
117 for start in range(2, len(chain)):
118 visited = {start}
119 elem = chain[start]
120 length = 1
121
122 while elem > 1 and elem <= max_num and elem not in visited:
123 visited.add(elem)
124 elem = chain[elem]
125 length += 1
126
127 if elem == start and length > max_len:
128 max_len = length
129 min_elem = start
130
131 return min_elem
132
133
134def solution(max_num: int = 1000000) -> int:

Callers 1

solutionFunction · 0.85

Calls 1

addMethod · 0.45

Tested by

no test coverage detected