Max Contiguous Subarray

Max Contiguous Subarray

 

Given a list of integers, write a program to identify the contiguous sub-list that has the largest sum and print the sum. Any non-empty slice of the list with step size 1 can be considered as a contiguous sub-list. Input

The input will contain space-separated integers, denoting the elements of the list. Output

The output should be an integer. Explanation

For example, if the given list is [2, -4, 5, -1, 2, -3], then all the possible contiguous sub-lists will be,

[2]

[2, -4]

[2, -4, 5]

[2, -4, 5, -1]

[2, -4, 5, -1, 2]

[2, -4, 5, -1, 2, -3]

[-4]

[-4, 5]

[-4, 5, -1]

[-4, 5, -1, 2]

[-4, 5, -1, 2, -3]

[5]

[5, -1]

[5, -1, 2]

[5, -1, 2, -3]

[-1]

[-1, 2]

[-1, 2, -3]

[2]

[2, -3]

[-3]

Among the above contiguous sub-lists, the contiguous sub-list [5, -1, 2] has the largest sum which is 6.

Sample Input 1

2 -4 5 -1 2 -3

Sample Output 1

6

Sample Input 2

-2 -3 4 -1 -2 1 5 -3

Sample Output 2

7

Answer:

numbers = [int(item) for item in input().split()]

maxSum = 0

maxTemp = 0

for i in range(0, len(numbers)):

maxTemp += numbers[i]

if maxTemp < 0:

maxTemp = 0

elif (maxSum < maxTemp):

maxSum = maxTemp

print(f'{maxSum}’)

 

Looking for Solutions?

Get the best assignment assistance from experts.

Order-Your-Assignment

Content Page Removal Request:

If you are the original writer or copyright-authorized owner of this article/post and no longer wish to have, your work published www.assignmenttask.com, then please email us with page link. help@Assignmenttask.Com