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!
CodePudding user response:
You should just be able to
max(arr, key=abs)
CodePudding user response:
Linear scaling is not bad, and there is very little practical difference between O(3N) and O(N). Since it would be impossible to determine (in an unordered list) that you've found the biggest or smallest without searching the entire list, O(N) is the best you can ask for.
That being said you could find what you're looking for in one pass by comparing the absolute value of each number (as you iterate) to the absolute value of the biggest or smallest number you've found so far.