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
- Free shipping in Python
- Raj has ordered two electronic items Python | Assignment Expert
- Team Points in Python
- Ticket selling in Cricket Stadium using Python | Assignment Expert
- Split the sentence in Python
- String Slicing in JavaScript
- First and Last Digits in Python | Assignment Expert
- List Indexing in Python
- Date Format in Python | Assignment Expert
- New Year Countdown in Python
- Add Two Polynomials in Python
- Sum of even numbers in Python | Assignment Expert
- Evens and Odds in Python
- A Game of Letters in Python
- Sum of non-primes in Python
- Smallest Missing Number in Python
- String Rotation in Python
- Secret Message in Python
- Word Mix in Python
- Single Digit Number in Python
- Shift Numbers in Python | Assignment Expert
- Weekend in Python
- Shift Numbers in Python | Assignment Expert
- Temperature Conversion in Python
- Special Characters in Python
- Sum of Prime Numbers in the Input in Python