LeetCode - 485. Max Consecuritive Onesアレイ


質問する


https://leetcode.com/problems/max-consecutive-ones/
Given a binary array nums, return the maximum number of consecutive 1's in the array.
配列内の連続する「1」の最大値を返します.
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

に答える


これはJavaです.
1.整数が1の場合、countが加算されます.
2.count値がresultより大きい場合は、結果値にcount値を加えます.
3.整数が0の場合、countは0に初期化されます.
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int result =0;
        int count = 0;
        for(int a : nums){
            if(a==1){
                count++;
                if(result<count) result=count;
            }else count=0;
        }
        return result;
    }
}