I have a numpy array like this [1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]
I'd like to find the length of the longest consecutive series of either 1s or -1s. In the example, it should be 3
Run a loop from start to end and if the current element is not equal to the previous (element+1) then set the count to 1 else increase the count. Update max with a maximum of count and max. First sort the array to arrange them in consecutive fashion. Now, store the distinct elements from the sorted array.
Naive Approach: A normal approach will be to iterate for every element and find out the longest increasing subsequence. For any particular element, find the length of the subsequence starting from that element. Print the longest length of the subsequence thus formed. The time complexity of this approach will be O(n2).
A simple solution is to use two nested loops. In the outer loop, we look for positive elements. In the inner loop, we count number of positives starting with the positive element picked by outer loop. Time complexity of this solution is O(n^2).
In pure Python
>>> from itertools import groupby
>>> L = [1,1,1,-1,-1,1,-1,1,1,-1,-1,-1,1,-1]
>>> max(sum(1 for i in g) for k,g in groupby(L))
3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With