May 04, 2020

#LeetCode: Max Consecutive Ones

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:
Input: [1,1,0,1,1,1]
Output: 3

Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

The input array will only contain 0 and 1.
The length of input array is a positive integer and will not exceed 10,000

1). Declare two variables max and tempmax.
2). Start iterating the array, if the current number is 1 increment tempmax.
3). If we encounter 0, and tempmax is greater than max, we will assign tempmax to max.
4). To improve the performance we can check if the max is greater than or equal to half of the array length, we will return max as there is no point in checking the array further.
5). When we encounter 0, we will reset tempmax to 0.
6). At the end we will return max or tempmax, whichever is greater.

Java Solution:

ALSO CHECKOther LeetCode Solutions in Java

-K Himaanshu Shuklaa..

No comments:

Post a Comment

RSSChomp Blog Directory