0

Algorithm looks correct, not able to figure out where the mistake is. Code returns from 8 to 10 is max subarray with total of 32. But actual answer is 8 to 11 with total of 43.

import sys
import math

def maxtuple(lss,rss):
  if lss[2] > rss[2]:
      return lss
  else:
      return rss

def crosssubarray(A, start, mid, end):
  ls=rs=-sys.maxsize
  maxleft=0
  maxright=0
  sum = 0;
  for i in reversed(range(start, mid)):
    sum = sum + A[i]
    print(i)
    if sum > ls:
        ls = sum
        maxleft = i
  sum = 0
  for i in range(mid+1, end):
    sum = sum+ A[i]
    if sum > rs:
        rs = sum
        maxright = i
  return (maxleft, maxright, ls+rs)

def maxsubarray(A,start,end):
  if start == end:
    return (start,end,A[start])
  else:
    mid = (start+end)/2
    lss = maxsubarray(A, start, mid)
    rss = maxsubarray(A, mid+1, end)
    css = crosssubarray(A, start, mid, end)
    maxsub = maxtuple(lss,rss)
    maxall = maxtuple(maxsub, css)
    return maxall`enter code here`

A = [13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7]
print(maxsubarray(A,0,15))
1
  • sorry, the acutal output should be 7 to 10 with total 43 Commented Jun 5, 2017 at 6:29

1 Answer 1

1

The problem is that range(start, mid) produces start,start+1,..,mid-1 but does not include mid.

This means that your crosssubarray does not include the middle value.

Instead try:

for i in reversed(range(start, mid+1)):
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.