JavaAlgorithms/Maths/AbsoluteMax.java

35 lines
818 B
Java
Raw Normal View History

2019-10-07 19:49:06 +08:00
package Maths;
import java.util.Arrays;
/**
* description:
2020-10-24 18:23:28 +08:00
*
* <p>absMax([0, 5, 1, 11]) = 11, absMax([3 , -10, -2]) = -10
2019-10-07 19:49:06 +08:00
*/
public class AbsoluteMax {
2020-10-24 18:23:28 +08:00
public static void main(String[] args) {
int[] testnums = {-2, 0, 16};
assert absMax(testnums) == 16;
int[] numbers = {3, -10, -2};
System.out.println("absMax(" + Arrays.toString(numbers) + ") = " + absMax(numbers));
}
2019-10-07 19:49:06 +08:00
2020-10-24 18:23:28 +08:00
/**
* get the value, return the absolute max value
*
* @param numbers contains elements
* @return the absolute max value
*/
public static int absMax(int[] numbers) {
int absMaxValue = numbers[0];
for (int i = 1, length = numbers.length; i < length; ++i) {
if (Math.abs(numbers[i]) > Math.abs(absMaxValue)) {
absMaxValue = numbers[i];
}
2019-10-07 19:49:06 +08:00
}
2020-10-24 18:23:28 +08:00
return absMaxValue;
}
2019-10-07 19:49:06 +08:00
}