Sponsored
Sponsored
This approach involves iterating through the array and counting sequences of 1s. If a 0 is encountered, the count is reset to 0. We keep track of the maximum count during the iteration.
Time Complexity: O(n), where n is the number of elements in the array, as we make a single pass.
Space Complexity: O(1) since no extra space proportional to input size is used.
1using System;
2
3public class MaxConsecutiveOnes {
4 public static int FindMaxConsecutiveOnes(int[] nums) {
5 int maxCount = 0, currentCount = 0;
6 foreach (int num in nums) {
7 if (num == 1) {
8 currentCount++;
9 maxCount = Math.Max(maxCount, currentCount);
10 } else {
11 currentCount = 0;
12 }
13 }
14 return maxCount;
15 }
16
17 public static void Main() {
18 int[] nums = {1, 1, 0, 1, 1, 1};
19 Console.WriteLine("The maximum number of consecutive 1s is: " + FindMaxConsecutiveOnes(nums));
20 }
21}
22
This C# method uses a foreach
loop to process the input array. The max consecutive count is determined using logic similar to that in the provided C# code, leveraging the static method Math.Max
for comparison.
This Python solution applies the same technique using the right
index iterating over the list, dynamically adjusting the left
boundary when it hits zero.