C# 2798번 블랙잭
2022. 1. 10. 13:17ㆍ코딩테스트 문제 풀이/[백준] 브루트 포스
728x90
반응형
코드 :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _1
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
string second = Console.ReadLine();
string[] inputdata = input.Split(' ');
int N = Convert.ToInt32(inputdata[0]);
int M = Convert.ToInt32(inputdata[1]);
string[] secondData = second.Split(' ');
int[] secondInt = new int[secondData.Length];
for (int i = 0; i < secondData.Length; i++)
{
secondInt[i] = Convert.ToInt32(secondData[i]);
}
//두번째 줄 데이터 오름차순 정리
Array.Sort(secondInt);
int output = blackJack(M, secondInt);
Console.WriteLine(output);
}
public static int blackJack(int M, int[] secondInt)
{
int first;
int second;
int third;
int max = 0;
int sum;
for (int i = 0; i < secondInt.Length; i++)
{
first = Convert.ToInt32(secondInt[i]);
for (int j = i+1; j < secondInt.Length; j++)
{
second = Convert.ToInt32(secondInt[j]);
if (M >= (first + second))
for (int k = j + 1; k < secondInt.Length; k++)
{
third = Convert.ToInt32(secondInt[k]);
if (M >= (first + second + third))
{
sum = (first + second + third);
if (max == 0)
max = sum;
if ((M - sum) <= M - max)
{
max = sum;
}
}
else
break;
}
else
break;
}
}
return max;
}
}
}
코드 풀이 :
두번째 줄에 들어오는 값을 오름차순으로 정렬한다.
이유는 만약 첫 번째 줄에서 5 15 가 들어오고 두번째 줄에서 5 6 7 8 9가 들어온다면
인덱스 순으로 5,6을 먼저 고르고 7을 골랐을 때, 이미 15를 초과하기 때문에 그 뒤에 값인 8,9를 확인해볼 필요가 없기 때문이다.
위와 같은 방법으로 첫 번째와 두 번째 카드는 이중포문을 통해 인덱스별로 올라가면서 뽑도록하고 기준값을 넘을시 break를 걸어 불필요한 비교는 하지 않는다.
깃허브 :
https://github.com/CheongHo-Lee/Algorithm-Study
GitHub - CheongHo-Lee/Algorithm-Study: Algorithm Study For Coding Test
Algorithm Study For Coding Test. Contribute to CheongHo-Lee/Algorithm-Study development by creating an account on GitHub.
github.com
728x90
반응형
'코딩테스트 문제 풀이 > [백준] 브루트 포스' 카테고리의 다른 글
C# 1436번 영화감독 숌 (0) | 2022.01.10 |
---|---|
C# 1018번 체스판 다시 칠하기 (0) | 2022.01.10 |
C# 7568번 덩치 (0) | 2022.01.10 |
C# 2231번 분해합 (0) | 2022.01.10 |