Your Input: 1 -2147483648 1 2 2 1 2 Expected output is -2147483646 how is absolute value be negative?


#1

Your Input: 1 -2147483648 1 2 2 1 2
Expected output is -2147483646

how is absolute value be negative??


#2

Hi,

In the example you mentioned:
-2147483648 is the negative extreme for 32 bit unsigned.

Also, in that example,
maxValue = 2,
minValue = -2147483648

So, abs(2 - (-2147483648)) = abs(2147483650)
but 2147483650 is greater than 2147483647 (maximum possible positive value).

So overflow happens. Also, 2147483650 in bit notation is-> 10000000000000000000000000000010 therefore it will be treated as negative number by 32-bit compiler and so calculates 2’s compliment of it which is -2147483646. And that is the expected answer.

But if you are doing absolute then you may get 2147483646.

However, if you use python where size of numbers are automatically increased you will get the result as 2147483650 but if you use Java or C++ where size of int is fixed to 4 bytes you will get -2147483646.

Thanks for posting the corner case, it will help others to avoid wrong submission !


#3

Thank you for the response it was a great explanation.


#4

your array is not sorted so how can this be a test case