简体   繁体   中英

Finding the maximum of absolute numbers

Is there any quick way of turning all the members of an array into absolute and find the max number among them? For example in this array:

-100 25 43

The max is 43, but I want to get 100 from my code. Is there's any simple/fast method that I can use to find max regardless of its sign? or do I have to use a for loop to turn all the array members into absolute and then find the max among them?

Try this:

int[] array = {-100, 25, 43};
int max = array.Select(Math.Abs).Max();

This works:

var numbers = new[] { -100, 25, 43 };

var absoluteMax = numbers.Select(x => Math.Abs(x)).Max();

I get 100 as requested.

Do be careful if one of your numbers is int.MinValue then you get an OverflowException - "Negating the minimum value of a twos complement number is invalid."

Well think about it. You have a list of numbers. You need to find the (absolute) maximum. Can you think of a way of finding the maximum without checking all of them? If you check the first 2, can you confidently conclude that you found the maximum, without checking the rest of the array? You can't. Thus, you need to check every single number.

A basic for loop would do. You don't have any better way than looping. Sure, you can use LINQ or other API's that hide the loop from you, but fundamentally that's what they do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM