[BOJ] 2562 - 최댓값 (Java)

EunBeen Noh·2023년 11월 8일

Algorithm

목록 보기
11/52

알고리즘

  • 구현

1. 문제

//예제 입력
3
29
38
12
57
74
40
85
61

//예제 출력
85
8

2. Idea

  • 각 입력줄마다 크기를 비교하면서 최댓값 update

  • 각 입력줄에 번호(index)를 부여 -> 별도의 배열을 생성하지 않아도 됨

3. 풀이

3.1. 변수 선언 및 초기화

  • int index: 각 입력 줄의 번호(몇 번째 입력 수인지 알기 위함), 1로 초기화

  • int result: 해당 시점의 최댓값

int index=1;
int result=1;

3.2. 각 입력 순회 및 대소비교

for(int i=0;i<8;i++){
	int next_num=Integer.parseInt(sc.nextLine());
	index++;
	if(next_num>max){result=index; max=next_num;}
}

3.3. 결과 출력

System.out.println(max);
System.out.print(result);

4. 전체코드

//Bronze_최댓값
import java.util.*;
public class BOJ_2562 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int max=Integer.parseInt(sc.nextLine());
        int index=1;
        int result=1;

        for(int i=0;i<8;i++){
            int next_num=Integer.parseInt(sc.nextLine());
            index++;
            if(next_num>max){result=index; max=next_num;}
        }
        System.out.println(max);
        System.out.print(result);
    }
}

0개의 댓글