코딩테스트/자바
[do it 알고리즘] 백준 1546 (배열과 리스트)
100세까지 코딩
2023. 9. 19. 16:11
문제 설명

풀기 전 생각
- 배열 생성 후 하나씩 저장
- Arrays.sort를 사용하여 정렬 후 최대값(M)찾기
- 배열을 순회하며 총합 구하기
- 계산식을 묶어 (총합 * 100 / M / N) 으로 평균 구하기
import java.util.Arrays;
import java.util.Scanner;
public class Baek1546 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] arr = new int[N];
int sum = 0;
for(int j = 0; j < arr.length; j++){
arr[j] = sc.nextInt();
}
Arrays.sort(arr);
for(int j = 0; j < arr.length; j++){
sum += arr[j];
}
double avg = (double)sum * 100 / arr[N-1] / N;
System.out.println(avg);
}
}
오류 및 개선
- 오류는 없지만 배열에 저장하지 않고 바로 구할 수 있음
- 메모리 및 시간 성능 향상
최종
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int max = 0;
int sum = 0;
for(int j = 0; j < N; j++){
int score = sc.nextInt();
max = score > max ? score : max;
sum += score;
}
double avg = (double)sum * 100 / max / N;
System.out.println(avg);
}
}