2-line concise O(N) time O(1) space solution (with explanation)


  • 0
        int findMaxConsecutiveOnes(vector<int>& x) {
          for (int i = 0, res = 0, cur = 0; i <= x.size(); res = max(res, ++cur*=x[i++]))
            if (i == x.size()) return res;
        }
    

    Note: ++cur*=x[i] is just to update cur, the current number of consecutive ones:

    • if x[i] == 1, increment cur by 1;
    • if x[i] == 0, reset cur = 0.

Log in to reply
 

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