Maximum continuous sub-array:
problem:
Given a sequence of n integers (possibly negative) a [1], a [2], a [3], ..., a [n], find the sequence as a [i] + a [i + 1] +… + The maximum value of the sum of subsections of a [j]. When the given integers are all negative, the sub-segment sum is defined as 0. According to this definition, the optimal value is: Max {0, a [i] + a [i + 1] +… + a [j]} , 1 <= i <= j <= n
For example, when (a [1], a [2], a [3], a [4], a [5], a [6]) = (-2,11, -4,13, -5,- 2), the maximum sub-segment sum is 20.
Divide and conquer:
def Max_cross_sum(list1,left,mid,right):
left_sum = 0
right_sum = 0
temp = 0
mid_1 = mid
while mid_1>=left:
temp += list1[mid_1]
left_sum = max(left_sum,temp)
mid_1 -= 1
temp = 0
mid_1 = mid + 1
while mid_1<=right:
temp += list1[mid_1]
right_sum = max(right_sum,temp)
mid_1 += 1
return left_sum+right_sum
def Max_sum(list1,left,right):
if left == right:
return list1[left]
mid = (left+right)//2
left_sum = Max_sum(list1,left,mid)
right_sum = Max_sum(list1,mid+1,right)
cross_sum = Max_cross_sum(list1,left,mid,right)
return max(left_sum,max(right_sum,cross_sum))
list1 = [-2,1,-3,4,-10,2,10,-5,6]
Max_sum(list1,0,len(list1)-1)
Dynamic programming method:
def Max_sum(lis1):
temp = 0
max_sum = 0
for cnt in list1:
temp = max(temp+cnt,cnt)
max_sum = max(max_sum,temp)
return max_sum
list1 = [-2,1,-3,4,-1,2,10,-5,1]
Max_sum(list1)