topcoderの問題をやってみようかなシリーズ。
動的計画法で絞って簡単な方から少しずつやり始めている。
今回のは、SRMCardsという問題。
https://community.topcoder.com/stat?c=problem_statement&pm=10240
キーポイントは、同じ数のカードが存在しない。
dp[i]:i番まででmaxターン数
public class SRMCards {
public int maxTurns(int[] cards) {
int[] dp = new int[cards.length];
dp[0] = 1;
Arrays.sort(cards);
for (int i = 1; i < cards.length; i++) {
if (cards[i - 1] + 1 == cards[i]) {
if (i >= 2) {
dp[i] = dp[i - 1] == dp[i - 2] ? dp[i - 1] + 1 : dp[i - 1]; //連続した3つの数の場合は +1しなければいけない。
} else {
dp[i] = 1;
}
} else {
dp[i] = dp[i - 1] + 1;
}
}
return dp[cards.length - 1];
}
}