Open In App

Python | Maximum Sum Sublist

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The task is to find a contiguous sublist (i.e., a sequence of elements that appear consecutively in the original list) such that the sum of the elements in this sublist is as large as possible. We need to return the maximum sum of this sublist. Let’s explore methods to find Maximum Sum Sublist in python:

Kadane’s Algorithm (Optimal Approach)

Approach

Kadane’s algorithm uses dynamic programming to solve the problem in a single pass. This approach involves:

  • At each index, decide whether to start a new sublist or continue the existing sublist by adding the current element.
  • Keep track of the best (maximum) sum found so far.

Code:

Python
def kadane(arr):

    max_sum = float('-inf')
    cur_sum = 0
    
    for x in arr:
      
        # Either add x to the existing subarray or start fresh from x
        cur_sum = max(x, cur_sum + x)
        
        # Update global maximum
        max_sum = max(max_sum, cur_sum)
    
    return max_sum

# Example usage:
if __name__ == "__main__":
    arr = [1, -3, 2, 1, -1]
    print(kadane(arr))

Output
3

Explanation:

  • Dynamic Programming: Use a variable (cur_Sum) to keep track of the best sublist ending at the current position.
  • Choose or Restart: At each element x, decide whether to add x to cur_Sumor start a new sum at x.
  • Global Maximum: Keep a separate max_sum that stores the maximum sum encountered so far.
  • Time Complexity: O(n)

Using For Loop (Brute Force Approach)

This method’s approach involves evaluating the sum of every possible sublist and keeping track of the maximum sum found. While this method is easy to understand, it is highly inefficient for large lists due to its cubic time complexity.

Python
def max_subarray(arr):
    n = len(arr)
    max_sum = float('-inf')
    
    for start in range(n):
        cur_sum = 0
        for end in range(start, n):
            cur_sum += arr[end]  # accumulate sum for subarray [start..end]
            if cur_sum > max_sum:
                max_sum = cur_sum
    
    return max_sum

# Example Usage
if __name__ == "__main__":
    arr = [1, -3, 2, 1, -1]
    print(max_subarray(arr))

Output
3

Explanation:

  • Nested Loops: We use two loops to explore all possible contiguous sublists.
  • Compute Sublist Sum: Inside the inner loop, we continuously add elements to a running sum.
  • Track Global Max: We update a max_sum variable whenever the current sum exceeds the previously recorded maximum.
  • Time Complexity: [Tex]O(n^2)[/Tex]


Next Article

Similar Reads