I want to find the maximum number from a list that has both positive, negative number and irrespective of sign. For example:
arr = [2,3,-6,5]
## output: -6
arr = [2,3,6,-5]
## output: 6
I've the following code which is working:
def max_number(l):
abs_maxval = max(l,key=abs)
maxval = max(l)
minval = min(l)
if maxval == abs_maxval:
return maxval
else:
return minval
Though this is working and the time complexity is O(N)
, I'm wondering if there is a way to find the number faster or optimize the code? From my understanding I'm scanning the list 3 times which might be slower for a large list and for my problem, I'm going through hundreds of thousands large lists.
Any suggestion will be helpful. Thanks!
You should just be able to
max(arr, key=abs)