Skip to content

Commit 2ad0171

Browse files
Arrays: 485. Max Consecutive Ones
1 parent 83ef1fe commit 2ad0171

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package arrays.easy;
2+
3+
/***
4+
* Problem 485 in Leetcode: https://leetcode.com/problems/max-consecutive-ones/
5+
*
6+
* Given a binary array nums, return the maximum number of consecutive 1's in the array.
7+
*
8+
* Example 1:
9+
* Input: nums = [1,1,0,1,1,1]
10+
* Output: 3
11+
*
12+
* Example 2:
13+
* Input: nums = [1,0,1,1,0,1]
14+
* Output: 2
15+
*/
16+
17+
public class MaxConsecutiveOnes {
18+
public static void main(String[] args) {
19+
int[] nums = {1, 1, 0, 1, 1, 1};
20+
21+
System.out.println("Number of One's: " + getMaxConsecutiveOnes(nums));
22+
}
23+
24+
private static int getMaxConsecutiveOnes(int[] nums) {
25+
int maxCount = 0, count = 0;
26+
27+
for (int i = 0; i < nums.length; i++) {
28+
if (nums[i] == 0) {
29+
count = 0;
30+
} else {
31+
count++;
32+
maxCount = Math.max(count, maxCount);
33+
}
34+
}
35+
36+
return maxCount;
37+
}
38+
}

0 commit comments

Comments
 (0)