가장 처음에 N×N크기에 사탕을 채워 놓는다. 사탕의 색은 모두 같지 않을 수도 있다. 상근이는 사탕의 색이 다른 인접한 두 칸을 고른다. 그 다음 고른 칸에 들어있는 사탕을 서로 교환한다. 이제, 모두 같은 색으로 이루어져 있는 가장 긴 연속 부분(행 또는 열)을 고른 다음 그 사탕을 모두 먹는다.
사탕이 채워진 상태가 주어졌을 때, 상근이가 먹을 수 있는 사탕의 최대 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 보드의 크기 N이 주어진다. (3 ≤ N ≤ 50)
다음 N개 줄에는 보드에 채워져 있는 사탕의 색상이 주어진다. 빨간색은 C, 파란색은 P, 초록색은 Z, 노란색은 Y로 주어진다.
functiongetSevenSmalls(arr) { let answer = [...arr]; let sum = arr.reduce((acc, cur) => acc + cur); let diff = sum - 100; for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === diff) { answer.splice(j, 1); answer.splice(i, 1); return answer.sort((a, b) => a - b).join("\n"); } } } }
console.log(getSevenSmalls(input));
해설
난쟁이 키의 합이 100이므로 9명의 키 합을 구한 뒤 2중 for문을 돌면서 나머지 2명의 키의 합이 차이와 같을 때, 2명을 제거한 배열을 반환하였다. function getMaxCandies(board) { const dx = [0, 1, 0, -1]; const dy = [1, 0, -1, 0]; let maxCandies = 1;
for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { for (let k = 0; k < 4; k++) { const nx = i + dx[k]; const ny = j + dy[k];
if (nx < 0 || ny < 0 || nx >= n || ny >= n) {
continue;
}
const temp = board[i][j];
board[i][j] = board[nx][ny];
board[nx][ny] = temp;
for (let l = 0; l < n; l++) {
let rowCandies = 1;
let colCandies = 1;
for (let m = 1; m < n; m++) {
if (board[l][m] === board[l][m - 1]) {
rowCandies++;
} else {
maxCandies = Math.max(maxCandies, rowCandies);
rowCandies = 1;
}
if (board[m][l] === board[m - 1][l]) {
colCandies++;
} else {
maxCandies = Math.max(maxCandies, colCandies);
colCandies = 1;
}
}
maxCandies = Math.max(maxCandies, rowCandies, colCandies);
}
const temp2 = board[i][j];
board[i][j] = board[nx][ny];
board[nx][ny] = temp2;
}
}