Implement the maximumConsecutiveOnes method that returns the longest run of consecutive 1 values.

The input contains a binary array nums and its length size. Each element is either 0 or 1.

Your task is to return the maximum number of consecutive 1 values present in the array. For example, in [1,1,0,1,1,1], the longest continuous group of ones has length 3.

Example 1

Input
nums (int[]) = [1,1,0,1,1,1]
size (int) = 6
Returns (int) 3

Example 2

Input
nums (int[]) = [1,0,1,1,0,1]
size (int) = 6
Returns (int) 2

Example 3

Input
nums (int[]) = [0,0,0]
size (int) = 3
Returns (int) 0

Scan the array once and count the current continuous group of ones.

When the current value is 1, increase the running count and update the best answer. When the current value is 0, reset the running count to zero because the consecutive sequence is broken.

The largest count seen during the scan is the answer.

Pseudocode:

function maximumConsecutiveOnes(nums, size):
    current = 0
    best = 0
    for i from 0 to size - 1:
        if nums[i] == 1:
            current++
            best = max(best, current)
        else:
            current = 0
    return best
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.