Given a binary array, find the maximum number of consecutive 1s in this array.git
Example 1:
oop
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.
Note:this
0
and 1
.Idea 1. Tow pointers, right pointer to loop the array, locate the first ones, then count the ones starting from the current position, then continue moving to the next zero position and locate the next one and repeat util finish looping the array.spa
Time complexity: O(N)code
Space complexity: O(1)blog
1 class Solution { 2 public int findMaxConsecutiveOnes(int[] nums) { 3 int maxLen = 0; 4 for(int i = 0; i < nums.length; ++i) { 5 if(nums[i] == 1) { 6 int j = i; 7 while(i < nums.length && nums[i] == 1) { 8 ++i; 9 } 10 maxLen = Math.max(maxLen, i-j); 11 } 12 } 13 return maxLen; 14 } 15 }
Idea 1.b Store the last zero index as prev, the consecutive ones is the either between two zeros or left edge of the array or right edge of the array or the whole array composed of zeros only.three
Time complexity: O(N)input
Space complexity: O(1)it
1 class Solution { 2 public int findMaxConsecutiveOnes(int[] nums) { 3 int prev = -1; 4 int maxLen = 0; 5 for(int i = 0; i < nums.length; ++i) { 6 if(nums[i] == 0) { 7 if(i > 0) { 8 maxLen = Math.max(maxLen, i - prev - 1); 9 } 10 while(i < nums.length && nums[i] == 0) { 11 ++i; 12 } 13 prev = i - 1; 14 } 15 } 16 17 maxLen = Math.max(maxLen, nums.length - prev -1); 18 return maxLen; 19 } 20 }
Idea 2. Dynamic programming, Let dp[i] be the count of 1s end at index iio
dp[i] = dp[i-1] + 1 if dp[i] = 1
dp[i] = 0 if dp[i] = 0
Time complexity: O(N)
Space complexity: O(1)
1 class Solution { 2 public int findMaxConsecutiveOnes(int[] nums) { 3 int curr = 0; 4 int maxLen = 0; 5 for(int num: nums) { 6 if(num == 1) { 7 ++curr; 8 maxLen = Math.max(maxLen, curr); 9 } 10 else { 11 curr = 0; 12 } 13 } 14 15 return maxLen; 16 } 17 }