var prices = [100, 180, 260, 590, 40, 310, 535, 10, 5, 3];
var biggest_profit = 0;
for (var i = 0; i < prices.length; i++) { // outer loop
var first_price = prices[i];
for (var j = i + 1; j <= prices.length; j++) { // inner loop
// do something here
}
}
In the first iteration of the outer loop (i = 0), the inner loop executes N
times.
In the second iteration of the outer loop (i = 1), the inner loop executes N - 1
times.
In the third iteration of the outer loop (i = 2), the inner loop executes N - 2
times.
.
.
.
In the N - 2
th iteration of the outer loop (i = N - 3), the inner loop executes 3
times.
In the N - 1
th iteration of the outer loop (i = N - 2), the inner loop executes 2
times.
In the last (N
th) iteration of the outer loop (i = N - 1), the inner loop executes 1
time.
Therefore, the total number of times this code executes is
N
+ N - 1
+ N - 2
+ N - 3
+ … + 2
+ 1
= 1
+ 2
+ … + N - 3
+ N - 2
+ N - 1
+ N
Substituting this in the Sum of Natural numbers Formula,
= (N)(N + 1) / 2
= ((N^2) + N) / 2
= O(N^2)
, assuming // do something here
executes in constant time O(1)
.
——————
Also, do take a look at these
- https://stackoverflow.com/a/71805214/17112163
- https://stackoverflow.com/a/71146522/17112163
- https://stackoverflow.com/a/69821878/17112163
- https://stackoverflow.com/a/71537431/17112163
- https://stackoverflow.com/a/72046933/17112163