# Program to find sum of contiguous sublist with maximum sum in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 := A

• 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

Live Demo

class Solution(object):
def solve(self, nums):
dp = [0 for i in range(len(nums))]
dp = nums
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