Home > Software design >  The code showing Time Limit Exceed erroe, could some one explain, where is problem in this code
The code showing Time Limit Exceed erroe, could some one explain, where is problem in this code

Time:01-03

LeetCode 485 Given a binary array nums, return the maximum number of consecutive 1's in the array.

Example 1:

Input: nums = [1,1,0,1,1,1] Output: 3 Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

---------Solution:-------

public int findMaxConsecutiveOnes(int[] nums) {
    int maxConsSize = Integer.MIN_VALUE;
    
    int i = -1, j=-1, k=0;
    
    while(k<nums.length){
        while(k<nums.length && nums[k] == 1){
            k  ;
            i  ;
        }
        
        if(nums[k] == 0){
            maxConsSize = Math.max(maxConsSize,i-j);
            j = i;
        }
        
    }
    
    maxConsSize = Math.max(maxConsSize,i-j);
    
    return maxConsSize;
}

CodePudding user response:

Warning: This is not direct answer (for this "do my homework" question)

You should use (or learn to use) debugger in your IDE (trust me, IDE, e.g. Eclipse will help you a lot in your beginnings).

The easiest (I'm not saying smartest) way, how to know what the program is doing (when you need to know, like in this case) is to add some print statements, e.g. add System.out.println("k=" k) into your program (in a while loop).

You might want to watch this youtube video.

CodePudding user response:

You have an infinity loop. Try run this:

public class Test {
    public static void main(String[] args) {
        int maxConsSize = Integer.MIN_VALUE;
        int[] nums = {1,1,0,1,1,1};

        int i = -1, j=-1, k=0;
        System.out.println(nums.length);

        while(k<nums.length){
            while(k<nums.length && nums[k] == 1){
                k  ;
                i  ;
                System.out.println("k = "   k);
            }

            if(nums[k] == 0){
                maxConsSize = Math.max(maxConsSize,i-j);
                j = i;
            }

        }

        maxConsSize = Math.max(maxConsSize,i-j);

        System.out.println(maxConsSize);
    }
}

Output:

6
k = 1
k = 2

After reading the first 0 you are in infinite loop. You have made this task very complicated :)

It's probably not the best solution, but it should be faster

public int findMaxConsecutiveOnes(int[] nums) {
    int maxCons = 0;
    int currentCons = 0;
    for (int i = 0; i < nums.length; i  ) {
        if (nums[i] == 0) {
           if (currentCons > maxCons) {
              maxCons = currentCons;
           }
              currentCons = 0;
           } else {
              currentCons  ;
           }
        }

        if (currentCons > maxCons) {
            maxCons = currentCons;
        }
        
        return maxCons;
    }
}

CodePudding user response:

There are two basic forms of loops:

  1. for-each, for-i or sometimes called ranged for

    Use that for a countable number of iterations. For example having an array or collection to loop through.

  2. while and do-while (like until-loops in other programming languages)

    Use that for something that has a dynamic exit-condition. Bears the risk for infinite-loops!

Your issue: infinite loop

You used the second form of a while for a typical use-case of the first. When iterating over an array, you would be better to use any kind of for loop.

The second bears always the risk of infinite-loops, without having a proper exit-condition, or when the exit-condition is not fulfilled (logical bug). The first is risk-free in that regard.

Recommendation to solve

Would recommend to start with a for-i here:

// called for-i because the first iterator-variable is usually i
for(int i=0; i < nums.length, i  ) {
  // do something with num[i]
  System.out.println(num[i]):
}

because:

  • it is safer, no risk of infinite-loop
  • the iterations can be recognized from the first line (better readability)
  • no counting, etc. inside the loop-body

Even simpler and idiomatic pattern is actually to use a for each:

for(int n : nums) {
  // do something with n
  System.out.println(n):
}

because:

  • it is safer, no risk of infinite-loop
  • the iterations can be recognized from the first line (better readability)
  • no index required, suitable for arrays or lists
  • no counting at all

See also: Java For Loop, For-Each Loop, While, Do-While Loop (ULTIMATE GUIDE), an in-depth tutorial covering all about loops in Java, including concepts, terminology, examples, risks

  •  Tags:  
  • java
  • Related