n = int(input())
data = list(map(int, input().split()))
data.sort()
result = 0
count = 0 #현재 그룹에 포함된 모험가의 수
for i in data:
count += 1:
if count >= i: #현재 그룹에 포함된 모험가의 수 > 공포도
result += 1
count = 0
print(result)
자바
import java.util.*;
public class Main {
public static int n;
public static ArrayList<Integer> arrayList = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 0; i < n; i++) {
arrayList.add(sc.nextInt());
}
Collections.sort(arrayList);
int result = 0; // 총 그룹의 수
int count = 0; // 현재 그룹에 포함된 모험가의 수
for (int i = 0; i < n; i++) { // 공포도를 낮은 것부터 하나씩 확인하며
count += 1; // 현재 그룹에 해당 모험가를 포함시키기
if (count >= arrayList.get(i)) { // 현재 그룹에 포함된 모험가의 수가 현재의 공포도 이상이라면, 그룹 결성
result += 1; // 총 그룹의 수 증가시키기
count = 0; // 현재 그룹에 포함된 모험가의 수 초기화
}
}
System.out.println(result);
}
}
data = input()
result = int(data[0]) #첫 번째 문자를 숫자로 변경하여 대입
for i in range(1, len(data)):
num = int(data[i])
if num <= 1 or result <= 1:
result += num
else:
result *= num
print(result)
자바
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
// 첫 번째 문자를 숫자로 변경한 값을 대입
long result = str.charAt(0) - '0';
for (int i = 1; i < str.length(); i++) {
// 두 수 중에서 하나라도 '0' 혹은 '1'인 경우, 곱하기보다는 더하기 수행
int num = str.charAt(i) - '0';
if (num <= 1 || result <= 1) {
result += num;
}
else {
result *= num;
}
}
System.out.println(result);
}
}
data = input()
count0 = 0
count1 = 0
if data[0] == '1':
count0 += 1
else:
count1 += 1
for i in range(len(data) - 1:
if data[i] != data[i+1]:
if data[i + 1] == '1':
count0 += 1
else:
count1 += 1
print(min(count0, count1))
자바
import java.util.*;
public class Main {
public static String str;
public static int count0 = 0; // 전부 0으로 바꾸는 경우
public static int count1 = 0; // 전부 1로 바꾸는 경우
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
str = sc.next();
// 첫 번째 원소에 대해서 처리
if (str.charAt(0) == '1') {
count0 += 1;
}
else {
count1 += 1;
}
// 두 번째 원소부터 모든 원소를 확인하며
for (int i = 0; i < str.length() - 1; i++) {
if (str.charAt(i) != str.charAt(i + 1)) {
// 다음 수에서 1로 바뀌는 경우
if (str.charAt(i + 1) == '1') count0 += 1;
// 다음 수에서 0으로 바뀌는 경우
else count1 += 1;
}
}
System.out.println(Math.min(count0, count1));
}
}
정렬을 사용한 그리디 알고리즘
n = int(input())
data = list(map(int, input().split())
data.sort()
target = 1
for x in data:
if target < x:
break
target += x
print(target)
자바
import java.util.*;
public class Main {
public static int n;
public static ArrayList<Integer> arrayList = new ArrayList<>();
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
for (int i = 0; i < n; i++) {
arrayList.add(sc.nextInt());
}
Collections.sort(arrayList);
int target = 1;
for (int i = 0; i < n; i++) {
// 만들 수 없는 금액을 찾았을 때 반복 종료
if (target < arrayList.get(i)) break;
target += arrayList.get(i);
}
System.out.println(target);
}
}