Giri lekkala Giri lekkala - 1 month ago 7
Python Question

Python-How to find length of the longest run of monotonically increasing numbers?

How to find length of the longest run of monotonically increasing numbers in a given list ?

For example, if

L = [10, 4, 6, 8, 3, 4, 5, 7, 7, 2]
then function implementation should return the value
5
because the longest run of monotonically increasing integers in L is
[3, 4, 5, 7, 7]
.

Please suggest me the solution.

Answer

Keep a count which tracks monotonically increasing number and a 'maxCont' to track the highest count

def mCount(L):
    count=1

    maxCount=0
    for i in range(len(L)-1):
        if L[i+1] >= L[i]:
            count +=1
        else:

            count =1
        if maxCount<count:
            maxCount=count
    return maxCount

Demo:

print mCount([10, 4, 6, 8, 3, 4, 5, 7, 7, 2])

Output:

5