Skip to content

Instantly share code, notes, and snippets.

@samsonq
Last active November 21, 2022 22:24
Show Gist options
  • Save samsonq/520d146917b5a9bd2bf572ca6887fff6 to your computer and use it in GitHub Desktop.
Save samsonq/520d146917b5a9bd2bf572ca6887fff6 to your computer and use it in GitHub Desktop.
Second Largest O(n)
def second_largest(n):
first = n[0]
second = n[1]
if second > first:
first, second = second, first
for i in range(2, len(n)):
if n[i] > first:
first, second = n[i], first
if second > first:
first, second = second, first
elif (n[i] > second) and (n[i] < first):
second = n[i]
return second
x = [1, 2, 3, 4, 10, 9, 8, 7, 6, 5]
print(second_largest(x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment