[자바JAVA]백준 2562 최댓값 풀이

문제

9개의 서로 다른 자연수가 주어질 때, 이들 중 최댓값을 찾고 그 최댓값이 몇 번째 수인지를 구하는 프로그램을 작성하시오.
예를 들어, 서로 다른 9개의 자연수 3, 29, 38, 12, 57, 74, 40, 85, 61 이 주어지면, 이들 중 최댓값은 85이고, 이 값은 8번째 수이다.

  • 입출력예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//입력
3
29
38
12
57
74
40
85
61

//출력
85
8




풀이코드1

  • memory 11476 runtime 76
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Main {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int max = 0; //자연수가 주어지므로 선언을 Integer.MIN_VALUE이 아닌 0으로 함
int i = 0; //인덱스값
int[] arr = new int[9]; //서로 다른 9개의 자연수를 넣을 배열

// sol1 memory 11476 runtime 76

//배열에 숫자넣기 -> 배열이 있어야지 index값을 구할 수 있음
for(i=0; i<arr.length; i++){
arr[i] = Integer.parseInt(br.readLine());
max = Math.max(arr[i], max);
}

//배열 인덱스 구하기
for(int j =0; j<arr.length; j++){
if(arr[j] == max){
i = j+1;
}
}

System.out.println(max);
System.out.println(i);
}
}




풀이코드2 : for문 한번만 사용하기

  • memory 11444 runtime 76
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Main {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int max = 0; //자연수가 주어지므로 선언을 Integer.MIN_VALUE이 아닌 0으로 함
int i = 0; //인덱스값
int[] arr = new int[9]; //서로 다른 9개의 자연수를 넣을 배열


// sol2 for문 한번만 사용하기
// memory 11444 runtime 76
for(int j=0; j<arr.length;j++) {
arr[j] = Integer.parseInt(br.readLine());
if(max < arr[j]) {
max = arr[j];
i = j+1;
}
}

System.out.println(max);
System.out.println(i);
}
}




백준의 다른 문제 풀이가 보고싶다면?