-7

I want to find the second largest number such as this topic. Get the second largest number in a list in linear time

My problem is this restricting words list, [], remove, del, min, max, dict, {}, sort, pop.

I have no ideas to get the second largest number. Then, I want someone to suggest me.

Thanks!

Community
  • 1
  • 1
Fillry
  • 1

3 Answers3

2

Not sure I've understood correctly your question but the post you've mentioned is giving you already few good solutions. For instance, if you don't want to code the algorithm by yourself, use the standard library heapq like this:

import random
import heapq

random.seed(1)
el = [random.randint(1, 100) for i in range(20)]
print el
first_max, second_max = heapq.nlargest(2, el)
print "Max element is {0} and the second max {1}".format(first_max,
second_max)
Community
  • 1
  • 1
BPL
  • 9,632
  • 9
  • 59
  • 117
0
first_max=arr[0]
second_max=first_max
if(arr[0]>arr[1]):
    first_max=arr[0]
    second_max=arr[1]
for i in range(1,len(arr)):
    if(arr[i]>first_max):
       second_max=first_max
       first_max=arr[i]
    elif(arr[i]>second_max):
       second_max=arr[i]

print(second_max)

I think above code will work for all cases... try and let me know.

Lokesh Sanapalli
  • 1,012
  • 3
  • 18
  • 39
0

Try this ->

a = [1,5,7,8,3,4,6,8,2,9]
x=-999999999999
n=999999999999
for i in a:
    if i>x:
        x=i
for i in a:
    if x-i!=0 and x-i<n:
        n=x-i
        ans=i
print ans
jbsu32
  • 1,036
  • 1
  • 11
  • 31