Java 4 lines concise solution with explanation


  • 42
    Y
        public int findMaxConsecutiveOnes(int[] nums) {
            int maxHere = 0, max = 0;
            for (int n : nums)
                max = Math.max(max, maxHere = n == 0 ? 0 : maxHere + 1);
            return max; 
        } 
    

    The idea is to reset maxHere to 0 if we see 0, otherwise increase maxHere by 1
    The max of all maxHere is the solution

    110111
    ^ maxHere = 1
    
    110111
    .^ maxHere = 2
    
    110111
    ..^ maxHere = 0
    
    110111
    ...^ maxHere = 1
    
    110111
    ....^ maxHere = 2
    
    110111
    .....^ maxHere = 3
    

    We can also solve this problem by setting k = 0 of Max Consecutive Ones II


  • 0
    Z

    If the last number is 0, doesn't the result of your code will be 0?


  • 0
    G

    @zhangfan4530 In each iteration max will be updated, so if the last number is zero, then MAX will be picked from(max, 0), so MAX will be max.


  • 0
    S
    This post is deleted!

  • 0
    G

    @yuxiangmusic ok,actually we are the same :

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
        int cnt=0,ret=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==1){
                cnt++;
                ret=Math.max(ret,cnt);
            }else{cnt=0;}
        }
        return ret;
        }
    }
    

  • 0
    K

    Same idea, just make it easier to read with explanation. Thanks for sharing!

    class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            int max = 0;
            int sum = 0;
            for(int i = 0 ; i< nums.length; i ++){
                sum += nums[i];
                if(nums[i] == 0)    // reset sum to zero when encounters zeros
                    sum = 0;
                else                // keep update max
                    max = Math.max(max, sum);
            }
            return max;
        }
    }
    

  • 0
    R

    @yuxiangmusic said in Java 4 lines concise solution with explanation:

    public int findMaxConsecutiveOnes(int[] nums) {
        int maxHere = 0, max = 0;
        for (int n : nums)
            max = Math.max(max, maxHere = n == 0 ? 0 : maxHere + 1);
        return max; 
    } 
    

    I think it is concise, but not so efficient. You can just check max when you see 0, not every time.


Log in to reply
 

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