Leetcode: Max Consecutive Ones Solution in PHP
Given a binary array nums
, return the maximum number of consecutive 1
's in the array.
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 2
Constraints:
1 <= nums.length <= 105
nums[i]
is either0
or1
.
Hint:
You need to think about two things as far as any window is concerned. One is the starting point for the window. How do you detect that a new window of 1s has started? The next part is detecting the ending point for this window. How do you detect the ending point for an existing window? If you figure these two things out, you will be able to detect the windows of consecutive ones. All that remains afterwards is to find the longest such window and return the size.
Solution:
function findMaxConsecutiveOnes($nums) {
$maxCount = 0;
$currentCount = 0;
foreach($nums as $num) {
if ($num === 1) {
$currentCount += 1;
$maxCount = max($maxCount, $currentCount);
} else {
$currentCount = 0;
}
}
return $maxCount;
}
$nums = [1, 1, 0, 1, 1, 1];
echo findMaxConsecutiveOnes($nums); // Output: 3
Time and Space Complexity
Time Complexity: The loop iterates through the array once: O(N), where N is the number of elements in nums
.
Space Complexity: The solution uses O(1) additional space since only variables are used for tracking counts.