백준 블랙잭

Lee·2023년 4월 12일
0

알고리즘

목록 보기
23/24

문제

백준 블랙잭 문제 링크

나의 풀이

  1. N의 범위가 1~100까지 주어져 시간이 충분하다고 생각하여 완전탐색을 사용해 3중 반복문을 통해 카드 3개를 합한 값을 구한후 비교하는 방식을 채택했다.
for i in range(n):
    for j in range(i+1, n):
        for k in range(j+1, n):
            temp = cards[i] + cards[j] + cards[k]
            if temp > m:
                continue
            else:
                result = max(result, temp)
  1. 문제 해결 후 100개의 카드 중 3개의 카드를 골라 합을 구하는 것은 combination 개념과 같아 itertools의 combinations을 사용해 문제를 해결해 보았다.
for cards in combinations(cards, 3):
    temp = sum(cards)
    if result < temp <= m:
        result = temp

코드

1. 3중 for문을 사용한 풀이

n, m = map(int, input().split())
cards = list(map(int, input().split()))

result = 0

for i in range(n):
    for j in range(i+1, n):
        for k in range(j+1, n):
            temp = cards[i] + cards[j] + cards[k]
            if temp > m:
                continue
            else:
                result = max(result, temp)

print(result)

2. combination을 사용한 풀이

from itertools import combinations

n, m = map(int, input().split())
cards = list(map(int, input().split()))

result = 0

for cards in combinations(cards, 3):
    temp = sum(cards)
    if result < temp <= m:
        result = temp

print(result)
profile
발전하고 싶은 백엔드 개발자

0개의 댓글