Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of contiguous sublist with maximum sum in Python
The Maximum Subarray Problem asks us to find the contiguous sublist within an array that has the largest sum. This is a classic problem that can be efficiently solved using Kadane's Algorithm with dynamic programming.
For example, given the array [-2, 1, -3, 4, -1, 2, 1, -5, 4], the maximum sum subarray is [4, -1, 2, 1] with sum 6.
Algorithm Approach
We use dynamic programming to solve this problem efficiently ?
Create an array
dpof the same size as input arraySet
dp[0] = A[0](first element)-
For each position
ifrom 1 to n-1:dp[i] = max(dp[i-1] + A[i], A[i])
Return the maximum value in
dp
Implementation
Here's the complete implementation using dynamic programming ?
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)
# Test the solution
nums = [-2, 1, -3, 7, -2, 2, 1, -5, 4]
solution = Solution()
result = solution.solve(nums)
print(f"Array: {nums}")
print(f"Maximum subarray sum: {result}")
Array: [-2, 1, -3, 7, -2, 2, 1, -5, 4] Maximum subarray sum: 8
Optimized Space Solution
We can optimize space complexity by using only two variables instead of an array ?
def max_subarray_sum(nums):
if not nums:
return 0
current_sum = nums[0]
max_sum = nums[0]
for i in range(1, len(nums)):
current_sum = max(nums[i], current_sum + nums[i])
max_sum = max(max_sum, current_sum)
return max_sum
# Test with different arrays
test_arrays = [
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
[-2, 1, -3, 7, -2, 2, 1, -5, 4],
[1, 2, 3, 4, 5],
[-1, -2, -3, -4]
]
for arr in test_arrays:
result = max_subarray_sum(arr)
print(f"Array: {arr}")
print(f"Maximum sum: {result}")
print()
Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4] Maximum sum: 6 Array: [-2, 1, -3, 7, -2, 2, 1, -5, 4] Maximum sum: 8 Array: [1, 2, 3, 4, 5] Maximum sum: 15 Array: [-1, -2, -3, -4] Maximum sum: -1
How It Works
At each position, we make a decision: either extend the previous subarray by including the current element, or start a new subarray from the current element. We choose whichever gives us a larger sum.
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| DP Array | O(n) | O(n) | Learning/debugging |
| Optimized | O(n) | O(1) | Production code |
Conclusion
Kadane's algorithm efficiently solves the maximum subarray problem in O(n) time. The optimized version uses constant space while maintaining the same time complexity.
