Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Sublist Maximum in custom sliced List
Next article icon

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
Python - Sublist Maximum in custom sliced List
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • python-list
Practice Tags :
  • python
  • python-list

Similar Reads

  • Python - Maximum Sum Record
    Sometimes, while working with data, we might have a problem in which we need to find maximum sum between available pairs in list. This can be application to many problems in mathematics domain. Let’s discuss certain ways in which this task can be performed. Method #1 : Using max() + list comprehensi
    3 min read
  • Python - Incremental Sublist Sum
    Sometimes we need to group elements and grouping techniques and requirements vary accordingly. One such way to group the elements is by the i’th size in list which stores the dictionary of index keys with values of summation of subsequent size i. Let’s discuss certain ways in which this can be done.
    3 min read
  • Keys with Maximum value - Python
    In Python, dictionaries are used to store data in key-value pairs and our task is to find the key or keys that have the highest value in a dictionary. For example, in a dictionary that stores the scores of students, you might want to know which student has the highest score. Different methods to ide
    4 min read
  • Python - Sublist Maximum in custom sliced List
    Sometimes, while working with data, we can have a problem in which we need to extract maximum not of whole list but of certain customly broken sublists. This kind of problem is peculiar and occurs in many domains. Let's discuss certain ways in which in which this task can be performed. Method #1 : U
    5 min read
  • Python | Consecutive Subsets Minimum
    Some of the classical problems in programming domain comes from different categories and one among them is finding the minimum of subsets. This particular problem is also common when we need to accumulate the minimum and store consecutive group minimum. Let’s try different approaches to this problem
    4 min read
  • Python - Sort Matrix by K Sized Subarray Maximum Sum
    Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] Explanation : 12 = 12 = 12
    4 min read
  • Python | Index Maximum among Tuples
    Sometimes, while working with records, we might have a common problem of maximizing contents of one tuple with corresponding index of other tuple. This has application in almost all the domains in which we work with tuple records. Let’s discuss certain ways in which this task can be performed. Metho
    6 min read
  • Python - Merge elements of sublists
    In Python, we often need to combine multiple sublists into a single list. This can be useful when dealing with data that is organized in smaller chunks, like rows in a table or pages in a document. Using itertools.chain()itertools.chain() function is one of the most efficient ways to merge sublists.
    4 min read
  • Python - Concatenate Maximum Tuples
    Given a tuple list with string and its magnitude, the task is to write a python program to join all the strings with maximum magnitudes. Examples: Input : test_list = [("Gfg is best", 8), ("gfg is good", 7), ("for", 2), ("for all geeks", 8)]Output : "Gfg is best for all geeks" Explanation : 8 is max
    8 min read
  • Python | Custom List slicing Sum
    The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done. Me
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences