Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the longest down sequence in a Java array

Given this array

int [] myArray = {5,-11,2,3,14,5,-14,2};

I must be able to return 3 because the longest down sequence is 14,5,-14. What's the fastest way to do this?

PS: Down sequence is a series of non-increasing numbers.

like image 340
Derek Long Avatar asked Sep 24 '26 02:09

Derek Long


2 Answers

another implementation in python:

def longest_down_sequence(seq):
    max = 0
    current_count = 0
    last = None
    for x in seq:
        if x <= last: current_count += 1
        else: current_count = 1
        if current_count > max: max = current_count
        last = x
    return max
like image 160
gtrak Avatar answered Sep 26 '26 17:09

gtrak


Just make one pass through the list of numbers. Pseudocode:

bestIndex = 0
bestLength = 0

curIndex = 0
curLength = 1

for index = 1..length-1
   if a[index] is less than or equal to a[index-1]
       curLength++
   else 
       //restart at this index since it's a new possible starting point
       curLength = 1
       curIndex = index

   if curLength is better than bestLength
       bestIndex = curIndex
       bestLength = curLength

next          

Note: You can ditch any line containing bestIndex or curIndex if you don't care about knowing where that subsequence occurs, as seen in Gary's implementation.

like image 28
Mark Peters Avatar answered Sep 26 '26 17:09

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!