I am solving this problem using Python, and I don\'t really know how to do the s
ID: 3755062 • Letter: I
Question
I am solving this problem using Python, and I don't really know how to do the second question!!!! I have my code at the bottom, please continue with my code and solve question 2(if possible, question3 as well)!!! Thx!!!!
def segmentMax(alist):
if len(alist) <2:
return sum(alist)
else:
midpoint=len(alist)//2
segment1=segmentMax(alist[:midpoint])
segment2=segmentMax(alist[midpoint:])
segment3=midmax(alist)
return max(segment1,segment2,segment3)
def midmax(alist):
rightmost = 0
leftmost= 0
sum1=0
sum2=0
midpoint=len(alist)//2
for i in range(midpoint):
sum1 = sum1+ alist[midpoint+i]
if sum1>rightmost:
rightmost=sum1
for i in range(midpoint):
sum2 = sum2+alist[midpoint-i-1]
if sum2>leftmost:
leftmost=sum2
return leftmost+rightmost
maxsum = [-8,4,-2,5,7,-8,19,-3,0,1]
print(segmentMax(maxsum))
Explanation / Answer
Python3:
# The code is same except the return value. We are returning an array instead of a single value. array will contain maximum sum and the let and right index of
# segment. and then we will compare all the segments and return the segment containing highest value and its left and right value.
import math
def midmax(alist,low,high):
r,l,s1,s2=0,0,0,0
mid=(low+high)//2
li,ri=mid,mid
for i in range(mid-1,low-1,-1):
s1+=alist[i]
if(s1>l):
l=s1
li=i
for i in range(mid+1,high+1):
s2+=alist[i]
if(s2>r):
r=s2
ri=i
var=l+r+alist[mid]
if(var>l and var>r):
return [var,li,ri]
elif(l>var and l>r):
return [l,low,mid-1]
else:
return [r,mid+1,high]
def segmentMax(alist,l,h):
if(l>h):
return [-math.inf,l,h]
else:
mid=(h+l)//2
seg1=segmentMax(alist,l,mid-1)
seg2=segmentMax(alist,mid+1,h)
seg3=midmax(alist,l,h)
if(seg1[0]>seg2[0] and seg1[0]>seg3[0]):
return seg1
elif(seg2[0]>seg1[0] and seg2[0]>seg3[0]):
return seg2
else:
return seg3
alist=[2,4,5,-7,3,-6,1,4]
n=len(alist)
seg=segmentMax(alist,0,n-1)
print("Segment from index",seg[1],"to",seg[2],"has maximum sum equal to",seg[0])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.