Problem statement:
In max contiguous subarray in Python, you are given a list of integers(positive and negative), and you have to find a sub-list from the given list which has the maximum sum and print the sum.
For example: list = [1, 6, -7, 5]
now, possible contiguous lists are:
[1]
[1, 6]
[1, 6, -7]
[1, 6, -7, 5]
[6]
[6, -7]
[6, -7, 5]
[-7]
[-7, 5]
[5]
Now, the list with the highest sum is the 2nd list having 7 as the total sum.
Now, let’s code the max sub-array problem.
Code for Max contiguous subarray in Python:
myList = [-1, 2, 4, -7, 5, -9] listOfSubLists = [] for i in range(len(myList)+1): for j in range(i+1, len(myList)+1): listOfSubLists.append(myList[i:j]) listOfAllSum = [] for i in listOfSubLists: listOfAllSum.append(sum(i)) max = -1 index = 0 for i in range(len(listOfAllSum)): if listOfAllSum[i]>max: max = listOfAllSum[i] index = i print('List with maximum sum is: ', listOfSubLists[index]) print('Maximum sum is: ', max)
Output:

Also Read:
- Hyphenate Letters in Python
- Earthquake in Python | Easy Calculation
- Striped Rectangle in Python
- Perpendicular Words in Python
- Composite Number in Python
- Greatest Among Four Numbers in Python
- Reverse the sentence in Python
- Denominations in Python
- Min and max values in an array in JavaScript
- Keyboard events in JavaScript
- Reaching Ground Floor in Python
- Number of Moves in Python
- Starks Adventure in Python
- Neutralization in Python | Assignment Expert
- Free shipping in Python
- Raj has ordered two electronic items Python | Assignment Expert
- First Place in Python
- Triples with Properties in Python
- Nested list Indexing Python
- Team Points in Python
- Two words combination in Python
- ID Card in Python
- Cipher with a key in Python | Assignment Expert
- Multiple of 5 in Python
- Sandglass Star in Python
- Multiple of 3 in Python | Assignment Expert
- Ticket selling in Cricket Stadium using Python | Assignment Expert
- Sum of List Elements in Python
- All possible subsets in Python
- Names and Nicknames in Python