aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--min_ops_bin_arr_1.c29
-rw-r--r--min_ops_bin_arr_1.py32
2 files changed, 61 insertions, 0 deletions
diff --git a/min_ops_bin_arr_1.c b/min_ops_bin_arr_1.c
new file mode 100644
index 0000000..c589165
--- /dev/null
+++ b/min_ops_bin_arr_1.c
@@ -0,0 +1,29 @@
+// 3191. Minimum Operations to Make Binary Array Elements Equal to One I
+#include "leetcode.h"
+
+/*
+ * you are given a binary array 'nums'. you can do the following operation on
+ * the array any number of times (possibly zero): choose any three consecutive
+ * elements from the array and flip all of them. flipping an element means
+ * changing its value from 0 to 1, and from 1 to 0. return the minimum number of
+ * operations required needed to make all elements in 'nums' equal to 1. if it
+ * is impossible, return -1.
+ */
+
+int minOperations(int *nums, int numsSize) {
+ int cnt = 0;
+ for (int i = 0; i < numsSize - 2; i++)
+ if (!nums[i]) {
+ nums[i] ^= 1;
+ nums[i + 1] ^= 1;
+ nums[i + 2] ^= 1;
+ cnt++;
+ }
+ return nums[numsSize - 2] && nums[numsSize - 1] ? cnt : -1;
+}
+
+int main() {
+ int n1[] = {0, 1, 1, 1, 0, 0}, n2[] = {0, 1, 1, 1};
+ printf("%d\n", minOperations(n1, ARRAY_SIZE(n1))); // expect: 3
+ printf("%d\n", minOperations(n2, ARRAY_SIZE(n2))); // expect: -1
+}
diff --git a/min_ops_bin_arr_1.py b/min_ops_bin_arr_1.py
new file mode 100644
index 0000000..eed3fea
--- /dev/null
+++ b/min_ops_bin_arr_1.py
@@ -0,0 +1,32 @@
+# 3191. Minimum Operations to Make Binary Array Elements Equal to One I
+
+"""
+you are given a binary array 'nums'. you can do the following operation on
+the array any number of times (possibly zero): choose any three consecutive
+elements from the array and flip all of them. flipping an element means
+changing its value from 0 to 1, and from 1 to 0. return the minimum number of
+operations required needed to make all elements in 'nums' equal to 1. if it
+is impossible, return -1.
+"""
+
+
+class Solution(object):
+ def minOperations(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ cnt, n = 0, len(nums)
+ for i in range(n - 2):
+ if nums[i] == 0:
+ nums[i] ^= 1
+ nums[i + 1] ^= 1
+ nums[i + 2] ^= 1
+ cnt += 1
+ return cnt if nums[n - 2] == 1 and nums[n - 1] == 1 else -1
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.minOperations(nums=[0, 1, 1, 1, 0, 0]))
+ print(obj.minOperations(nums=[0, 1, 1, 1]))