-1

The following code should have a run time of $O(N)$,

int min = INTEGER.MAX_VALUE;
int max = INTEGER.MIN_VALUE;

for (int x : array) {
    if (x < min) min = x;
    if (x > min) max = x;
}

but what about the following code?

int min = INTEGER.MAX_VALUE;
int max = INTEGER.MIN_VALUE;

for (int x : array) {
    if (x < min) min = x;
}
for (int x : array) {
    if (x > min) max = x;
}
Raphael
  • 73,212
  • 30
  • 182
  • 400
Anonymous Human
  • 197
  • 1
  • 4

1 Answers1

1

Its O(N). When there are consecutive loops, we calculate time complexity as sum of time complexities of individual loops.

for (int i = 1; i <=m; i += c) 
{  
        // some O(1) expressions
}
for (int i = 1; i <=n; i += c) 
{
        // some O(1) expressions
}

Time complexity of above code is O(m) + O(n) which is O(m+n) If m == n, the time complexity becomes O(2n) which is O(n).

Anjo
  • 372
  • 1
  • 9