-1

I want to implement an algorithm that finds the longest run of integers in an array recursively, using divide and conquer.

I made a sequential algorithm that makes sense, and I think I could do it using recursion. However, I am confused about how I would use divide and conquer, as I believe that would break up the run.

Example:

[1,2,3,4,4,4,3,3]

The first 4 would break off from the rest of the 4s, if the list was divided in half.

I already created the base case, but am unsure where to go from there.

Base case:

if(len(myarray) == 0):
    return 0
khelwood
  • 55,782
  • 14
  • 81
  • 108
chris
  • 1
  • 1
  • Could you define what "longest run of numbers" means? Right now it could mean anything like longest contiguous subarray or longest increasing subarray. Please be more specific while writing your questions – Nikhil Chatterjee Feb 08 '21 at 00:18

1 Answers1

0

You can detect a streak of numbers from the middle position expanding it on each side, and recurse on the remaining values to the left and right of that streak.

Return the longest of the 3 (longest-left, middle-streak, longest-right).

def maxrun(A,lo=None,hi=None):
    if lo is None: lo,hi = 0,len(A)-1  # start with the full range
    if lo > hi:  return 0              # empty sub range counts for zero
    if lo == hi: return 1              # single element subrange is one
    mid   = (lo+hi)//2                 # use value in middle of range
    left  = right = mid                # repeated range 
    while left>lo  and A[left-1]  == A[mid]: left  -= 1 # expand left
    while right<hi and A[right+1] == A[mid]: right += 1 # expand right
    return max(right-left+1,maxrun(A,lo,left-1),maxrun(A,right+1,hi)) # recurse


print(maxrun([1,2,3,4,4,4,3,3])) # 3

Note that this could be further optimized by only recursing down when the remaining range is larger than the current best streak.

Alain T.
  • 40,517
  • 4
  • 31
  • 51