private static int numberOfCards;
public int solution(int initialCoins, int[] cards) {
numberOfCards = cards.length;
boolean[] hand = new boolean[numberOfCards + 1];
boolean[] paid = new boolean[numberOfCards + 1];
int coinsLeft = initialCoins;
for (int i = 0; i < numberOfCards / 3; i++) {
hand[cards[i]] = true;
paid[cards[i]] = true;
}
int answer = 1;
for (int i = numberOfCards / 3; i < numberOfCards; i += 2) {
if (coinsLeft > 0) {
hand[cards[i]] = true;
hand[cards[i + 1]] = true;
}
boolean pass = false;
int minCost = 3;
int cardThrown = -1;
for (int j = 1; j <= numberOfCards; j++) {
if (!hand[j]) {
continue;
}
if (hand[numberOfCards + 1 - j]) {
int cost = (paid[j] ? 0 : 1) + (paid[numberOfCards + 1 - j] ? 0 : 1);
if (coinsLeft < cost || minCost <= cost) {
continue;
}
pass = true;
cardThrown = j;
minCost = cost;
}
}
if (!pass) {
break;
}
hand[cardThrown] = false;
hand[numberOfCards + 1 - cardThrown] = false;
coinsLeft -= minCost;
answer++;
}
return answer;
}
출처:https://school.programmers.co.kr/learn/courses/30/lessons/258707