Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the maximum of absolute numbers

Tags:

arrays

c#

max

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?

like image 561
Lily Avatar asked Oct 21 '25 11:10

Lily


2 Answers

Try this:

int[] array = {-100, 25, 43};
int max = array.Select(Math.Abs).Max();
like image 143
Vova Avatar answered Oct 22 '25 23:10

Vova


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."

like image 42
Enigmativity Avatar answered Oct 22 '25 23:10

Enigmativity



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!