1

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!

user3503711
  • 1,623
  • 1
  • 21
  • 32
  • 9
    Why not just `return max(l, key=abs)` ? – Andrej Kesely Sep 13 '22 at 20:59
  • Be reminded - *sort* can take *key* ...for any kind of func comparison. – Daniel Hao Sep 13 '22 at 21:02
  • You could easily remove the first pass through the list. After finding the `maxval` and `minval`, just compare their absolute values, and output the larger of the two. But you only need to do that if you have a preferred answer for a list like `[2,3,-6, 6, 5]`, where the answer could be either -6 or 6. If you don't have a preference, then `return max(l,key=abs)` will do the job in one pass. – user3386109 Sep 13 '22 at 21:22
  • 1
    Thanks, didn't see that coming! @AndrejKesely – user3503711 Sep 13 '22 at 21:35

2 Answers2

5

You should just be able to

max(arr, key=abs)
cmd
  • 5,754
  • 16
  • 30
1

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.

Portal
  • 124
  • 1