To find the largest three elements in a single pass over the array, we can maintain three variables to store the three largest elements found so far. As we iterate through the array:
If the current element is larger than the largest of the three, update the three variables accordingly.
If the current element is larger than the second largest but not the largest, update the second and third largest elements.
If the current element is larger than the third largest but not the other two, update the third largest element.
Initialize three variables first, second, and third to store the largest, second largest, and third largest elements respectively. Set them to very low values initially.
Traverse the array once, updating the variables based on the current element’s value compared to the three largest elements found so far.
After traversal, the three variables will contain the largest three elements.
classSolution:
deffindLargestThree(self, arr: List[int]) -> List[int]:
if len(arr) <3:
raiseValueError("Array must have at least three elements.")
first: int = float('-inf')
second: int = float('-inf')
third: int = float('-inf')
for num in arr:
if num > first:
third = second
second = first
first = num
elif num > second:
third = second
second = num
elif num > third:
third = num
return [first, second, third]
# Example usage:solution = Solution()
print(solution.findLargestThree([10, 4, 3, 50, 23, 90])) # Output: [90, 50, 23]print(solution.findLargestThree([12, 13, 1, 10, 34, 1])) # Output: [34, 13, 12]