Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Find Maximum Consecutive Ones in Array using Loop - Optimal Algorithm



Problem Statement

You are given a binary array that consists only of 0s and 1s. Your task is to find the maximum number of consecutive 1s that appear in the array.

In simpler terms, you need to count the longest stretch of 1s that are placed next to each other (without any 0s in between).

If the array is empty, the result should be 0.

Examples

Input ArrayMax Consecutive 1sDescription
[1, 1, 0, 1, 1, 1]3The longest sequence of 1s is [1, 1, 1]
[1, 1, 1, 1]4All elements are 1s, so the count is the length of the array
[0, 0, 0]0No 1s in the array
[1, 0, 1, 0, 1]1All 1s are isolated by 0s
[0, 1, 1, 0, 1, 1, 1, 0]3There are two sequences: [1, 1] and [1, 1, 1]; the longest is length 3
[1]1Single element that is 1
[0]0Single element that is 0
[]0Empty array should return 0

Solution

To solve this problem, we need to count how many 1s appear consecutively in the array. Whenever we encounter a 0, we know the streak is broken and we reset our count.

Let’s break it down:

  • We start scanning the array from the beginning.
  • Each time we see a 1, we increase a temporary counter (say current_count).
  • If we see a 0, that means the current sequence has ended, so we reset current_count to 0.
  • Throughout the loop, we also keep track of the highest value current_count has reached — that’s our max_count.

Let’s understand different scenarios:

  • Normal case: If the array has both 1s and 0s, we look for the longest continuous stretch of 1s between 0s. For example, in [1, 1, 0, 1, 1, 1], the answer is 3.
  • All 1s: If the array contains only 1s (like [1, 1, 1, 1]), then the entire array is one long stretch — the answer is the length of the array.
  • All 0s: If the array contains only 0s, there are no 1s, so the answer is 0.
  • Isolated 1s: If every 1 is surrounded by 0s (like [1, 0, 1]), then the maximum stretch is just 1.
  • Empty array: If the array has no elements, then clearly there are no 1s to count — we return 0.

This method uses a single loop and no extra space, making it extremely efficient. It works in O(n) time where n is the number of elements in the array.

Visualization

Algorithm Steps

  1. Given an array arr that contains only 0 and 1.
  2. Initialize two counters: max_count = 0 and current_count = 0.
  3. Iterate through the array:
  4. → If the current element is 1, increment current_count.
  5. → If the current element is 0, reset current_count to 0.
  6. After each step, update max_count if current_count is greater.
  7. After the loop, return max_count.

Code

Python
JavaScript
Java
C++
C
def max_consecutive_ones(arr):
    max_count = 0
    current_count = 0
    for num in arr:
        if num == 1:
            current_count += 1
            max_count = max(max_count, current_count)
        else:
            current_count = 0
    return max_count

# Sample Input
arr = [1, 1, 0, 1, 1, 1]
print("Max Consecutive Ones:", max_consecutive_ones(arr))

Time Complexity

CaseTime ComplexityExplanation
Best CaseO(n)Even if the array starts with a long streak of 1s, we still need to check all elements to ensure it's the longest sequence.
Average CaseO(n)The algorithm goes through each element of the array once in a single pass, updating counters as needed.
Average CaseO(n)In the worst case, such as alternating 1s and 0s, every element must still be processed to determine the maximum streak.

Space Complexity

O(1)

Explanation: The algorithm uses only two variables to keep track of the current and maximum count. No additional space is required.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M