
Math.max()와 Math.min() 메서드를 사용하면 두 수 간의 최대값, 최소값을 쉽게 구할 수 있습니다.
int a = 10;
int b = 20;
int max = Math.max(a, b);
int min = Math.min(a, b);
Math.max()와 Math.min()은 int, long, float, double 모두 지원합니다.// ❌ 아래는 컴파일 에러
int result = Math.max(10, 20, 30); // 에러: 인자가 3개!
중첩 호출 가능
int max = Math.max(Math.max(10, 20), 30); // OK
if 조건문 사용
int[] arr = {5, 3, 7, 1, 9};
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int n : arr) {
if (n < min) {
min = n;
}
if (n > max) {
max = n;
}
}
System.out.println("MAX: "+max);
System.out.println("MIN: "+min);
Math.max(), Math.min() 사용
int[] arr = {5, 3, 7, 1, 9};
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int n : arr) {
max = Math.max(max, n);
min = Math.min(min, n);
}
System.out.println("MAX: "+max);
System.out.println("MIN: "+min);
두 방식 모두 시간복잡도는 O(n)입니다.
--> n개의 요소를 한 번씩 순회하기 때문에
사실 Math.max()도 내부적으로는 if를 사용하기 때문에, 속도 차이가 거의 없습니다.