haechandev
Algorithms

[Baekjoon 2798] Blackjack

My first algorithm exercise: checking every combination of three cards.

February 22, 2022

I started with an easy problem for my first algorithm exercise.

Choose three of N cards and find the largest sum that does not exceed M. My first solution checked every possible three-card combination.

import sys

N, M = map(int, sys.stdin.readline().split())
num = list(map(int, sys.stdin.readline().split()))
high_value = 0

for first in range(N - 2):
    num1 = num[first]
    for second in range(N - 2 - first):
        num2 = num[first + second + 1]
        for third in range(N - 2 - first - second):
            num3 = num[first + second + third + 2]
            value = num1 + num2 + num3
            if high_value < value <= M:
                high_value = value

print(high_value)

It felt repetitive at first, but it taught me to exhaust all valid possibilities within the problem’s limits. I wanted to keep looking for simpler or better algorithms afterward.

Original post: View source