Easy C++ solutions:


  • 0
    A
    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int ans = 0, cur = 0, k = -1;
            for (int i = 0; i < nums.size(); ++i) {
                if (nums[i])
                    ++cur;
                else {
                    if (k < 0)
                        ++cur;
                    else
                        cur = i - k;
                    k = i;
                }
                ans = max(ans, cur);
            }
            return ans;
        }
    };
    

    a more concise one:

    class Solution {
    public:
        int findMaxConsecutiveOnes(vector<int>& nums) {
            int ans = 0, cur = 0, k = -1;
            for (int i = 0; i < nums.size(); ++i) {
                cur = (nums[i] || k < 0) ? cur + 1 : i - k;
                k = nums[i] ? k : i;
                ans = max(ans, cur);
            }
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.