Answer the question
In order to leave comments, you need to log in
How to parse the complexity of a nested loop algorithm?
I read the book "Algorithms for Beginners", there is an example:
The difference in the value of shares on a particular day is the number
of consecutive days, from the one we have chosen and back, until the day on which the value was less than or equal to the value on the day we have chosen.
function simpleStockSpan(arr){ //arr- курсы акций.
var result = [];
for(var i = 0; i < arr.length; i++){
var k = 1; //Минимальная разница
var spanEnd = false;
while( i - k >= 0 && !spanEnd ){
if(arr[i - k] <= arr[i]){
k += 1;
}
else{
spanEnd = true;
}
}
result.push(k);
}
return result;
}
Answer the question
In order to leave comments, you need to log in
"where did n*(n+1)/2 come from" is the sum of an arithmetic progression, in books on algorithms it is assumed that you own the school curriculum in mathematics.
"where did 1 to n + n to 1 come from?" - from the same place, this is an empirical description of the formula for the sum of an arithmetic progression: if you add the last number to the first number, the penultimate number to the second, and so on, then the sum of each pair will be n + 1, and there are n pairs in total, which means that if all pairs are added, then there will be n ( n + 1), but since here we used two sums from 1 to n instead of one, then for the original problem the answer must be divided in half - we get n (n + 1) / 2.
All of the above does not change the fact that the presentation of the material in your book is terrible.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question