Python/online judge

백준 [2798.블랙잭] | Python

구름솜:D 2024. 1. 29. 15:49
728x90

✏️ 문제

https://www.acmicpc.net/problem/2798

 

2798번: 블랙잭

첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장

www.acmicpc.net

 

✏️ 풀이방법

1. m에 최대한 가까운 카드를 합하기 위해 sort()메소드로 card를 정렬한다.

2. 3중 for문으로 x,y,z에 카드 세장을 뽑아 m에 가까운 최대합을 뽑는다.

 

 

📌 코드

n,m =  map(int,input().split())
card = list(map(int,input().split()))
card.sort()
maxtotal = []
for x in range(0,len(card)-2):
    for y in range(x+1,len(card)-1):
        for z in range(y+1,len(card)):
            total = card[x]+card[y]+card[z]
            if total <= m:
                maxtotal.append(total)
print(max(maxtotal))

 

 

📌 결과

#입력
5 21
5 6 7 8 9

#출력
21
#입력
10 500
93 181 245 214 315 36 185 138 216 295

#출력
497

 

 

🔎 다른풀이

from itertools import permutations

N, M = map(int, input().split())
lst = list(map(int, input().split()))
nlst = []

for three in permutations(lst, 3):
    if sum(three) > M:
        continue
    else:
        nlst.append(sum(three))
print(max(nlst))

- https://afterdawncoding.tistory.com/63
from itertools import combinations

card_num, target_num = map(int, input().split())
card_list = list(map(int, input().split()))
biggest_num = 0

for cards in combinations(card_list, 3):
    temp_sum = sum(cards)
    if biggest_sum < temp_sum <= target_sum:
        biggest_sum = temp_sum

print(biggest_sum)

-https://cdragon.tistory.com/52

-  파이썬에서 제공되는 순열, 조합 라이브러리 itertools모듈 활용 

 

 

📝 메모

- 라이브러리 공부하기