
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find sum of contiguous sublist with maximum sum in Python
Suppose we have an array A. We have to find the contiguous sublist which has the maximum sum, and also return its sum. So if the array A is like A = [-2,1,-3,4,-1,2,1,-5,4], then the sum will be 6. And the subarray will be [4, -1, 2, 1].
To solve this we will try to use Dynamic programming approach.
define an array dp same as the size of A, and fill it with 0
dp[0] := A[0]
for i := 1 to size of A – 1
dp[i] := maximum of dp[i – 1] + A[i] and A[i]
return max in dp
Let us see the following implementation to get better understanding −
Example
class Solution(object): def solve(self, nums): dp = [0 for i in range(len(nums))] dp[0] = nums[0] for i in range(1,len(nums)): dp[i] = max(dp[i-1]+nums[i],nums[i]) return max(dp) nums = [-2,1,-3,7,-2,2,1,-5,4] ob1 = Solution() print(ob1.solve(nums))
Input
[-2,1,-3,7,-2,2,1,-5,4]
Output
8
- Related Articles
- Program to find the maximum sum of circular sublist in Python
- Python program to find Sum of a sublist
- Program to find sum of the sum of all contiguous sublists in Python
- Program to find length of contiguous strictly increasing sublist in Python
- Program to find the sum of largest K sublist in Python
- Maximum contiguous sum of subarray in JavaScript
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find maximum product of contiguous subarray in Python
- Program to find maximum sum of multiplied numbers in Python
- Program to find size of smallest sublist whose sum at least target in Python
- Program to find sum of the minimums of each sublist from a list in Python
- Program to find maximum sum obtained of any permutation in Python
- Program to find maximum absolute sum of any subarray in Python
- Program to convert one list identical to other with sublist sum operation in Python

Advertisements