Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created March 19, 2025 16:06
Show Gist options
  • Save tatsuyax25/0c4c096550d0369190c9462aaef76c8c to your computer and use it in GitHub Desktop.
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,
/**
* @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