Created
March 19, 2025 16:06
-
-
Save tatsuyax25/0c4c096550d0369190c9462aaef76c8c to your computer and use it in GitHub Desktop.
You are given a binary array nums. You can do the following operation on the array any number of times (possibly zero): Choose any 3 consecutive elements from the array and flip all of them.
Flipping an element means changing its value from 0 to 1,
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var minOperations = function(nums) { | |
let count = 0; // Initialize the counter for the number of flips | |
// Helper function to flip a single element at index i | |
function flip(i) { | |
nums[i] = nums[i] === 0 ? 1 : 0; // Toggle the element (0 -> 1, 1 -> 0) | |
} | |
// Traverse the array, stopping at the third-to-last element | |
for (let i = 0; i < nums.length - 2; i++) { | |
// If the current element is 0, perform a flip operation on the group of 3 | |
if (nums[i] === 0) { | |
count++; // Increment the flip counter | |
flip(i); // Flip the current element | |
flip(i + 1); // Flip the next element | |
flip(i + 2); // Flip the element after that | |
} | |
} | |
// If there are still any 0s left in the array, return -1 (impossible case) | |
if (nums.includes(0)) { | |
return -1; | |
} | |
// Otherwise, return the total number of flip operations performed | |
return count; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment