C# - 2 counters - works with input stream, no memory


  • 1

    you can use 2 counters, one counter has already used it's zero flip and the other has not. When you see a zero the one that has already used it's flip must reset and the one that has not yet used it it's zero uses it now. The counter which is lesser is the the one that has not used it's zero.

        public int FindMaxConsecutiveOnes(int[] nums) 
        {
            int max = 0;
            int curr1 = 0;
            int curr2 = 0;
            
            foreach (int x in nums)
            {
                curr1++;
                curr2++;
                
                if (x == 0)
                {
                    // reset larger current
                    if (curr1 > curr2) curr1 = 0;
                    else curr2 = 0;
                }
                
                max = Math.Max(max, Math.Max(curr1, curr2));
            }
            
            return max;
        }
    

  • 0

    Smart Approach.


Log in to reply
 

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