485. Max Consecutive Ones
leetcode easy
#array#csharp#easy#leetcode#math#search
Task
Дан бинарный массив nums, верните максимальное количество последовательных единиц в массиве.
Пример:
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.
C# solution
matched/originalpublic class Solution {
public int FindMaxConsecutiveOnes(int[] nums) {
int count = 0;
int maxCount = 0;
foreach (int num in nums) {
if (num == 1) {
count += 1;
} else {
maxCount = Math.Max(maxCount, count);
count = 0;
}
}
return Math.Max(maxCount, count);
}
}C++ solution
auto-draft, review before submit#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public int FindMaxConsecutiveOnes(vector<int>& nums) {
int count = 0;
int maxCount = 0;
foreach (int num in nums) {
if (num == 1) {
count += 1;
} else {
maxCount = max(maxCount, count);
count = 0;
}
}
return max(maxCount, count);
}
}Java solution
matched/originalclass Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int maxCount = 0;
for (int num : nums) {
if (num == 1) {
count += 1;
} else {
maxCount = Math.max(maxCount, count);
count = 0;
}
}
return Math.max(maxCount, count);
}
}JavaScript solution
matched/originalvar findMaxConsecutiveOnes = function(nums) {
let count = 0
let maxCount = 0
for (let num of nums) {
if (num === 1) {
count += 1
} else {
maxCount = Math.max(maxCount, count)
count = 0
}
}
return Math.max(maxCount, count)
}Python solution
matched/originalclass Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
count = 0
maxCount = 0
for num in nums:
if num == 1:
count += 1
else:
maxCount = max(maxCount, count)
count = 0
return max(maxCount, count)Go solution
matched/originalfunc findMaxConsecutiveOnes(nums []int) int {
count := 0
maxCount := 0
for _, num := range nums {
if num == 1 {
count++
} else {
if count > maxCount {
maxCount = count
}
count = 0
}
}
if count > maxCount {
maxCount = count
}
return maxCount
}Explanation
Algorithm
Поддерживайте счетчик для подсчета единиц и увеличивайте его на 1 при встрече единицы.
Когда встречаете ноль, используйте текущий счетчик единиц для нахождения максимального количества последовательных единиц на данный момент, затем сбросьте счетчик единиц на 0.
В конце верните максимальное значение.
😎