function maxConsecutiveOnesAfterGame(T, testCases) {
const results = [];
for (let t = 0; t < T; t++) {
const N = testCases[t][0];
let board = testCases[t][1].split('');
let ones = [];
let zeros = [];
for (let i = 0; i < N; i++) {
if (board[i] === '1') {
ones.push(i);
} else {
zeros.push(i);
}
}
let turn = 0; // 0 for Roy, 1 for Emon
while (zeros.length > 0) {
if (turn === 0) { // Roy's turn
// Roy picks a '0' that would increase or start a sequence of 1's
let bestZero = -1;
let maxGain = -1;
for (let i = 0; i < zeros.length; i++) {
let index = zeros[i];
let leftIsOne = index > 0 && board[index - 1] === '1';
let rightIsOne = index < N - 1 && board[index + 1] === '1';
let gain = (leftIsOne ? 1 : 0) + (rightIsOne ? 1 : 0);
if (gain > maxGain) {
maxGain = gain;
bestZero = i;
}
}
if (bestZero !== -1) {
// Flip the selected zero
board[zeros[bestZero]] = '1';
zeros.splice(bestZero, 1);
}
} else {
let bestOne = -1;
let maxLoss = -1;
for (let i = 0; i < ones.length; i++) {
let index = ones[i];
// Simulate flipping this one to zero
let leftIsOne = index > 0 && board[index - 1] === '1';
let rightIsOne = index < N - 1 && board[index + 1] === '1';
let loss = (leftIsOne ? 1 : 0) + (rightIsOne ? 1 : 0);
if (loss > maxLoss) {
maxLoss = loss;
bestOne = i;
}
}
if (bestOne !== -1) {
// Flip the selected one
board[ones[bestOne]] = '0';
ones.splice(bestOne, 1);
}
}
// Alternate turns
turn = 1 - turn;
}
let maxConsecOnes = 0;
let currentConsec = 0;
for (let i = 0; i < N; i++) {
if (board[i] === '1') {
currentConsec++;
maxConsecOnes = Math.max(maxConsecOnes, currentConsec);
} else {
currentConsec = 0;
}
}
results.push(maxConsecOnes);
}
return results;
}
const T = 2;
const testCases = [
[2, "10"],
[3, "010"]
];
console.log(maxConsecutiveOnesAfterGame(T, testCases));