O
O
Ohurmevshiy2019-06-15 20:59:22
Algorithms
Ohurmevshiy, 2019-06-15 20:59:22

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.

The book presents a pseudo-code that I wrote in js (so far in ES5):
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;
}

5d0530b252c4a033399456.jpeg
I still don't understand where n*(n+1)/2 from 1+2+...+n came from? Why is it doubled? From the number of cycles or what? Why suddenly in "Non-obviousness of equality" appeared from 1 to n + from n to 1 ? This explanation really pissed me off.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Olohtonov, 2019-06-15
@Ohurmevshiy

"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 question

Ask a Question

731 491 924 answers to any question