|
| 1 | +# Explanation of the Code |
| 2 | + |
| 3 | +## **Objective** |
| 4 | +The program aims to count the minimum number of operations required to transform a binary array `nums` into a specific format where every element equals `1`. Each operation flips the value of three consecutive elements in the array (from `0` to `1` or vice versa). |
| 5 | + |
| 6 | +--- |
| 7 | + |
| 8 | +## **Step-by-Step Explanation** |
| 9 | + |
| 10 | +### **1. Initialize Variables** |
| 11 | +```java |
| 12 | +int n = nums.length; |
| 13 | +int count = 0; |
| 14 | + |
| 15 | +for (int i = 0; i <= n - 3; i++) { |
| 16 | + if (nums[i] == 0) { |
| 17 | + nums[i] = 1 - nums[i]; |
| 18 | + nums[i + 1] = 1 - nums[i + 1]; |
| 19 | + nums[i + 2] = 1 - nums[i + 2]; |
| 20 | + count++; |
| 21 | + } |
| 22 | +} |
| 23 | +This loop checks each element nums[i] in the array until n - 3 (ensuring there are at least three consecutive elements remaining). |
| 24 | + |
| 25 | +Condition (nums[i] == 0): |
| 26 | + |
| 27 | +If the current element is 0, it is flipped, along with the next two consecutive elements. |
| 28 | + |
| 29 | +This transformation ensures the first position of the current window becomes 1. |
| 30 | + |
| 31 | +count is incremented to record the operation. |
| 32 | + |
| 33 | +for (int i = n - 2; i < n; i++) { |
| 34 | + if (nums[i] != 1) { |
| 35 | + return -1; |
| 36 | + } |
| 37 | +} |
| 38 | +After completing transformations for three-element windows, the final two elements are checked: |
| 39 | + |
| 40 | +If either of them is not 1, it means the target format cannot be achieved, and the function returns -1. |
| 41 | + |
| 42 | +return count; |
| 43 | +If all elements are transformed into 1, the function returns the total number of operations required. |
| 44 | + |
| 45 | +Time Complexity |
| 46 | +First Loop (for i = 0 to n - 3): |
| 47 | + |
| 48 | +Iterates up to n - 3 elements, performing constant-time operations for each. Time Complexity: O(n) |
| 49 | + |
| 50 | +Second Loop (for i = n - 2 to n): |
| 51 | + |
| 52 | +Iterates over the last two elements of the array. Time Complexity: O(1) |
| 53 | + |
| 54 | +Overall Time Complexity: O(n) |
| 55 | + |
| 56 | +Space Complexity |
| 57 | +The program modifies the input array nums in-place and uses only a few integer variables (n, count, i). No additional data structures are required. |
| 58 | + |
| 59 | +Overall Space Complexity: O(1) |
0 commit comments