Java Solution with O(n) Complexity using ArrayList


  • 0
    G

    ...
    public class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {

     int retValue=0;	
       if(nums==null||nums.length==0) {
    	   return 0;
       }
       List<Integer> maxList = new  ArrayList<Integer>();
       int counter=0;
       int prevMax=0;
       for (int i=0;i<nums.length;i++) {
    	   if(nums[i]==1) {
    		   ++counter;
    		   if(i==nums.length-1) {
    			   prevMax = counter;
        		   if(!maxList.isEmpty()) {
        			   int curMax = maxList.get(0);
        			   if(curMax>prevMax) {
        				   continue;
        			   }
        			   else {
        				   maxList.set(0,prevMax); 
        			   }
        		   }
        		   else {
        			   maxList.add(prevMax); 
        		   }
    		   }
    	   }
    	   else {
    		   prevMax = counter;
    		   counter=0;
    		   if(!maxList.isEmpty()) {
    			   int curMax = maxList.get(0);
    			   if(curMax>prevMax) {
    				   continue;
    			   }
    			   else {
    				   maxList.set(0,prevMax); 
    			   }
    		   }
    		   else {
    			   maxList.add(prevMax); 
    		   }
    		 
    	   }    	
       }
       
       
       return maxList.get(0);
       
    
    }
    

    }
    ...
    ...


Log in to reply
 

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