Why does adding an IF statement inside of an IF statement makes the runtime 5 times slower?

Viewed 39

I solved the following question:

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

By writing a simple loop, that goes through the array, and sums the 1's. When it reaches a 0, it resets the 1's counter. Each time after adding 1 to the counter, it asks whether the maximum till now is bigger or not, and switches between them if needed.

So far so good. It works. This is my initial solution:

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0, curr =  0;
        for (int num: nums)
        {
            if (num == 1)
            {
                ++curr;
                if (curr > max)
                    max = curr;
            }
            else
                curr = 0;
        }
        return max;
    }
}

It takes 10ms to run it (runtime), and 56.7MB memory usage.

But then, I tried to get the 2nd IF statement outside the first one, and place it in the end of the loop.

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int max = 0, curr =  0;
        for (int num: nums)
        {
            if (num == 1)
            {
                ++curr;      
            }
            else
                curr = 0;
            
             if (curr > max)
                    max = curr;
        }
        return max;
    }
}

Now, the new runtime is only 2ms! and the memory usage is also smaller - 43.4MB.

My question is - Why?

I mean We have O(n) - runs through all the elements in the array either way. Then we have the IF-ELSE conditions, either way it checks if the elements is 1 or 0. And either way, it checks if curr > max?.

The only difference is that in the first way, it's located inside the first IF statement.

Why does it matter if we have the same operations - for o(n), if, if, else.

Thanks.

0 Answers
Related