본문 바로가기

JAVA

자바 최솟값, 최댓값 구하기 (백준 배열 2562, 10818 코드)

최솟값 또는 최댓값을 구하는 알고리즘은 항상 같다.

1) 결과값을 첫 번째 값으로 초기화시킨 후

2) 최솟값의 경우 다음 숫자가 더 작다면, 반대로 최댓값의 경우에는 크다면 결과값을 해당 값으로 업데이트한다.

   입력이 끝날때까지 숫자를 비교하며 이 과정을 반복한다.

 

< 백준 10818번 최소, 최대 정답 코드 >

// 입력 : 첫 번째 줄에 숫자의 개수, 두 번째 줄에 n개의 정수

// 출력 : 최솟값과 최댓값 

import java.io.*;

class Main{
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        String fline = br.readLine();
        int num = Integer.parseInt(fline);
        
        String sline = br.readLine();
        String[] slist = sline.split(" ");
        int[] ilist = new int[num];
        
        for(int i = 0; i<num; i++)
             ilist[i]= Integer.parseInt(slist[i]);
        
        int count = 0;
        int min = ilist[count], max = ilist[count]; //min, max값을 첫번째 값으로 초기화
        
        //min 구하기
        while(++count < num){
            if(ilist[count] < min)
                min = ilist[count];
        }
        
        //max 구하기
        count = 0;
        
        while(++count < num){
            if(ilist[count] > max)
                max = ilist[count];
        }

        String result = min + " " + max;
        
        bw.write(result);
            
        bw.flush();
    }    
}

 

 

< 백준 2562번 최댓값 정답 코드 >

// 입력 : 9줄 각각에 서로 다른 자연수가 주어짐 (<100)
// 출력 : 첫째줄에 최댓값, 둘째줄에 그 최댓값이 몇 번째 수인지 출력

import java.util.*;

class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int max = sc.nextInt();
        int num = 1;
        int count = 1;
        int cur;
        
        for(int i=2; i<10; i++){
            count++;
            cur = sc.nextInt();
            if(cur > max){
                max = cur;
                num = count;
            }
        }
        System.out.println(max+"\n"+num);
    }
}