485. Max Consecutive Ones
https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/
Given a binary array nums, return the maximum number of consecutive 1's in the array.
Answers
mine
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int curCount = 0;
int maxCount = 0;
for (int num : nums) {
if (num == 1) {
curCount++;
maxCount = Math.max(curCount, maxCount);
} else {
curCount = 0;
}
}
return maxCount;
}
}
/**
* Maintain current count and maximum count so far.
*
* Time Complexity: O(N)
*
* Space Complexity: O(1)
*
* N = Length of the input array
*/
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
if (nums == null) {
throw new IllegalArgumentException("Input array is null");
}
int curCount = 0;
int maxCount = 0;
for (int n : nums) {
if (n == 1) {
curCount++;
maxCount = Math.max(maxCount, curCount);
} else {
curCount = 0;
}
}
return maxCount;
}
}
Things I Learned
Validation check
Math.max(a, b)
'【 개발 이야기 】 > coding test' 카테고리의 다른 글
초보자를 위한 코테 (0) | 2025.01.16 |
---|---|
[leetcode] (Array101) 88. Merge Sorted Array (0) | 2024.08.20 |
[leetcode] (Array101) 1089. Duplicate Zeros (0) | 2024.08.20 |
[leetcode] (Array101) 977. Squares of a Sorted Array (0) | 2024.08.13 |
[leetcode] (Array101) 1295. Find Numbers with Even number of Digits (4) | 2024.08.13 |