Easy Java solution


  • 2

    The result is made of "previous consecutive 1s" + 0 + "current consecutive 1s". Each time a 0 is encountered, the number of "current consecutive 1s" plus 1 becomes the number of "previous consecutive 1s".

     public int findMaxConsecutiveOnes(int[] nums) {
            int pre = 0;
            int cur = 0;
            int result = 0;
            for (int num: nums) {
                if (num == 1) {
                    cur++;
                } else {
                    pre = cur + 1;
                    cur = 0;
                }
                 result = Math.max(result, cur + pre);
            }
            return result;
        }
    

  • 0
    J

    Hi, May I ask if we are required to flip K 0 to 1, Should we change as following?

    public int findMaxConsecutiveOnes(int[] nums) {
    int pre = 0;
    int cur = 0;
    int result = 0;

        for (int num: nums) {
            if (num == 1) {
                cur++;
            } else {
                pre = cur + 1;
                
            }
             result = Math.max(result, cur + pre);
        }
        return result;
    }

  • 0

    @Jiawei_Wu I am sorry I don't understand. You are not inputting k in your code


Log in to reply
 

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