Maximum Subarray in Python

PythonServer Side ProgrammingProgramming

Suppose we have an integer array A. We have to find the contiguous subarrays which length will be at least one, and that has the largest 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 the 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 the 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 a better understanding −

Example (Python)

Live Demo

class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
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])
#print(dp)
return max(dp)
nums = [-2,1,-3,7,-2,2,1,-5,4]
ob1 = Solution()
print(ob1.maxSubArray(nums))

Input

nums = [-2,1,-3,7,-2,2,1,-5,4]

Output

8
Published on 08-Jan-2020 15:16:36