✔ BOJ_2217


첫 번째는
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] weight = new int[N];
for(int i=0;i<weight.length;i++){
weight[i]=sc.nextInt();
}
int min = weight[0];
for(int i=1;i<weight.length;i++){
min = Math.min(min, weight[i]);
}
System.out.println(min * N);
}
}
이렇게 풀었다. 예제를 보고 (각 로프의 최소중량 * 총 개수)가 답인줄 알았는데 당연하게도 아니었고~..
그 다음에 틀린 코드는
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] weight = new int[N];
for(int i=0;i<weight.length;i++){
weight[i]=sc.nextInt();
}
Arrays.sort(weight);
int w = weight[weight.length -1];
int count = 1;
int answer = w;
for(int i=weight.length-2; i>=0;i--){
w = weight[i];
count ++;
if(answer > w*count) break;
else answer = w*count;
}
System.out.println(answer);
}
}
요거
이 코드는 맞는 것 같은데 왜 틀린가하고 봤더니 예외가 있었다 ㅠㅠ
input이 8, 10, 3, 3, 3, 3, 3, 3, 3이면 return이 (3*8 = 24) 여야하는데 위의 코드로 하면 return이 10이 나오기 때문에 💧💧
그래서 고친게 아래 코드.
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class BOJ_2217 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int[] weight = new int[N];
for(int i=0;i<weight.length;i++){
weight[i]=sc.nextInt();
}
Arrays.sort(weight);
int w = weight[weight.length -1];
int count = 1;
int answer = w;
for(int i=weight.length-2; i>=0;i--){
w = weight[i];
count ++;
if(answer <= w*count) { answer = w*count;}
}
System.out.println(answer);
}
}
입력을 받고, 크기 순서대로 정렬하고(Arrays.sort()이용) 마지막부터 순서대로 꺼내면서 비교한다. 그 전 코드에서 answer가 이전 answer보다 작아지는 경우 break; 했다면 여기서는 answer가 이전 answer보다 크면 answer을 변경하는 식으로 코드를 짰다.