max, min 값 구하기

드코미·2025년 7월 21일
post-thumbnail

두 수의 최대/최소값 구하기

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

배열, 리스트에서 기본적인 for문 방식

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를 사용하기 때문에, 속도 차이가 거의 없습니다.

profile
할 수 있다!!!

0개의 댓글