짬뽕얼큰하게의 맨땅에 헤딩 :: Minimum Operations to Make Binary Array Elements Equal to One I

Leetcode Problem:

Summary

  • Given a binary array, find the minimum number of operations to make all elements equal to 1 by flipping 3 consecutive elements at a time.

Approach

  • The approach is to iterate through the array and flip 3 consecutive elements at a time until no more flips are possible
  • If a 3 consecutive elements cannot be found, return -1.

Complexity

  • O(n), where n is the number of elements in the array

Explanation

  • The solution iterates through the array and checks if the current element and the next two elements are 0
  • If they are, it flips them and increments the answer
  • This process continues until no more flips are possible
  • If at any point a 3 consecutive elements cannot be found, the function returns -1.

Solution Code:


class Solution {
public:
    int minOperations(vector& nums) {
        int ans = 0;
        for(int i = 0 ; i < nums.size(); i++){
            if(nums[i] == 0){
                for(int j = i; j < i + 3; j++){
                    if(j >= nums.size()) return -1;
                    nums[j] ^= 1;
                }
                ans++;
            }
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Find All Possible Recipes from Given Supplies  (0) 2025.03.21
Minimum Cost Walk in Weighted Graph  (0) 2025.03.20
Split Linked List in Parts  (0) 2025.03.19
Longest Nice Subarray  (0) 2025.03.18
Divide Array Into Equal Pairs  (0) 2025.03.17
블로그 이미지

짬뽕얼큰하게

,