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
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Longest subarray having maximum sum
Next article icon

Maximum Subarray Sum – Kadane’s Algorithm

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum.

Examples:

Input: arr[] = {2, 3, -8, 7, -1, 2, 3}
Output: 11
Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.

Input: arr[] = {-2, -4}
Output: –2
Explanation: The subarray {-2} has the largest sum -2.

Input: arr[] = {5, 4, 1, 7, 8}
Output: 25
Explanation: The subarray {5, 4, 1, 7, 8} has the largest sum 25.

Table of Content

  • [Naive Approach] By iterating over all subarrays – O(n^2) Time and O(1) Space
  • [Expected Approach] Using Kadane’s Algorithm – O(n) Time and O(1) Space

[Naive Approach] By iterating over all subarrays – O(n^2) Time and O(1) Space

The idea is to run two nested loops to iterate over all possible subarrays and find the maximum sum. The outer loop will mark the starting point of a subarray and inner loop will mark the ending point of the subarray.

C++
// C++ Program to find the maximum subarray sum using nested loops   #include <bits/stdc++.h> using namespace std;  // Function to find the sum of subarray with maximum sum int maxSubarraySum(vector<int> &arr) {     int res = arr[0];        // Outer loop for starting point of subarray   	for(int i = 0; i < arr.size(); i++) {     	int currSum = 0;                // Inner loop for ending point of subarray         for(int j = i; j < arr.size(); j++) {         	currSum = currSum + arr[j];                        // Update res if currSum is greater than res             res = max(res, currSum);         }     }     return res; }  int main() {     vector<int> arr = {2, 3, -8, 7, -1, 2, 3};     cout << maxSubarraySum(arr);     return 0; } 
C
// C Program to find the maximum subarray sum using nested loops  #include <stdio.h>  // Function to find the sum of subarray with maximum sum int maxSubarraySum(int arr[], int size) {     int maxSum = arr[0];        // Outer loop for starting point of subarray     for (int i = 0; i < size; i++) {         int currSum = 0;                // Inner loop for ending point of subarray         for (int j = i; j < size; j++) {             currSum = currSum + arr[j];                        // Update maxSum if currSum is greater than maxSum             if (currSum > maxSum) {                 maxSum = currSum;             }         }     }     return maxSum; }  int main() {     int arr[] = {2, 3, -8, 7, -1, 2, 3};     int size = sizeof(arr) / sizeof(arr[0]);     printf("%d", maxSubarraySum(arr, size));     return 0; } 
Java
// Java Program to find the maximum subarray sum using nested loops   import java.util.Arrays;  class GfG {      // Function to find the sum of subarray with maximum sum     static int maxSubarraySum(int[] arr) {         int res = arr[0];            // Outer loop for starting point of subarray         for (int i = 0; i < arr.length; i++) {             int currSum = 0;                    // Inner loop for ending point of subarray             for (int j = i; j < arr.length; j++) {                 currSum = currSum + arr[j];                                // Update res if currSum is greater than res                 res = Math.max(res, currSum);             }         }         return res;     }      public static void main(String[] args) {         int[] arr = {2, 3, -8, 7, -1, 2, 3};         System.out.println(maxSubarraySum(arr));     } } 
Python
# Python Program to find the maximum subarray sum using nested loops  # Function to find the sum of subarray with maximum sum def maxSubarraySum(arr):     res = arr[0]        # Outer loop for starting point of subarray     for i in range(len(arr)):         currSum = 0                # Inner loop for ending point of subarray         for j in range(i, len(arr)):             currSum = currSum + arr[j]                        # Update res if currSum is greater than res             res = max(res, currSum)                return res  if __name__ == "__main__":     arr = [2, 3, -8, 7, -1, 2, 3]     print(maxSubarraySum(arr)) 
C#
// C# Program to find the maximum subarray sum using nested loops  using System;  class GfG {          // Function to find the sum of subarray with maximum sum     static int MaxSubarraySum(int[] arr) {         int res = arr[0];            // Outer loop for starting point of subarray         for (int i = 0; i < arr.Length; i++) {             int currSum = 0;                    // Inner loop for ending point of subarray             for (int j = i; j < arr.Length; j++) {                 currSum = currSum + arr[j];                                // Update res if currSum is greater than res                 res = Math.Max(res, currSum);             }         }         return res;     }      static void Main() {         int[] arr = {2, 3, -8, 7, -1, 2, 3};         Console.WriteLine(MaxSubarraySum(arr));     } } 
JavaScript
// JavaScript Program to find the maximum subarray sum using nested loops   // Function to find the sum of subarray with maximum sum function maxSubarraySum(arr) {     let res = arr[0];        // Outer loop for starting point of subarray     for (let i = 0; i < arr.length; i++) {         let currSum = 0;                // Inner loop for ending point of subarray         for (let j = i; j < arr.length; j++) {             currSum = currSum + arr[j];                        // Update res if currSum is greater than res             res = Math.max(res, currSum);         }     }     return res; }  const arr = [2, 3, -8, 7, -1, 2, 3]; console.log(maxSubarraySum(arr)); 

Output
11

[Expected Approach] Using Kadane’s Algorithm – O(n) Time and O(1) Space

The idea of Kadane’s algorithm is to traverse over the array from left to right and for each element, find the maximum sum among all subarrays ending at that element. The result will be the maximum of all these values.

But, the main issue is how to calculate maximum sum among all the subarrays ending at an element in O(N) time?

To calculate the maximum sum of subarray ending at current element, say maxEnding, we can use the maximum sum ending at the previous element. So for any element, we have two choices:

  • Choice 1: Extend the maximum sum subarray ending at the previous element by adding the current element to it. If the maximum subarray sum ending at the previous index is positive, then it is always better to extend the subarray.
  • Choice 2: Start a new subarray starting from the current element. If the maximum subarray sum ending at the previous index is negative, it is always better to start a new subarray from the current element.

This means that maxEnding at index i = max(maxEnding at index (i – 1) + arr[i], arr[i]) and the maximum value of maxEnding at any index will be our answer.

Illustration:


Below is the implementation of the above algorithm:

C++
// C++ Program for Maximum Subarray Sum using Kadane's Algorithm  #include <bits/stdc++.h> using namespace std;  // Function to find the maximum subarray sum int maxSubarraySum(vector<int> &arr) {     int res = arr[0];     int maxEnding = arr[0];      for (int i = 1; i < arr.size(); i++) {                // Find the maximum sum ending at index i by either extending          // the maximum sum subarray ending at index i - 1 or by         // starting a new subarray from index i         maxEnding = max(maxEnding + arr[i], arr[i]);                // Update res if maximum subarray sum ending at index i > res         res = max(res, maxEnding);     }     return res; }  int main() {     vector<int> arr = {2, 3, -8, 7, -1, 2, 3};     cout << maxSubarraySum(arr);     return 0; } 
C
// C Program for Maximum Subarray Sum using Kadane's Algorithm  #include <stdio.h> #include <limits.h>  // Function to find the maximum subarray sum int maxSubarraySum(int arr[], int size) {     int res = arr[0];     int maxEnding = arr[0];      for (int i = 1; i < size; i++) {                  // Find the maximum sum ending at index i by either extending          // the maximum sum subarray ending at index i - 1 or by         // starting a new subarray from index i         maxEnding = (maxEnding + arr[i] > arr[i]) ?            									maxEnding + arr[i] : arr[i];                // Update res if maximum subarray sum ending at index i > res         res = (res > maxEnding) ? res : maxEnding;     }     return res; }  int main() {     int arr[] = {2, 3, -8, 7, -1, 2, 3};     int size = sizeof(arr) / sizeof(arr[0]);     printf("%lld\n", maxSubarraySum(arr, size));     return 0; } 
Java
// Java Program for Maximum Subarray Sum using Kadane's Algorithm  import java.util.Arrays;  class GfG {      // Function to find the maximum subarray sum     static int maxSubarraySum(int[] arr) {         int res = arr[0];         int maxEnding = arr[0];          for (int i = 1; i < arr.length; i++) {                          // Find the maximum sum ending at index i by either extending              // the maximum sum subarray ending at index i - 1 or by             // starting a new subarray from index i             maxEnding = Math.max(maxEnding + arr[i], arr[i]);                        // Update res if maximum subarray sum ending at index i > res             res = Math.max(res, maxEnding);         }         return res;     }      public static void main(String[] args) {         int[] arr = {2, 3, -8, 7, -1, 2, 3};         System.out.println(maxSubarraySum(arr));     } } 
Python
# Python Program for Maximum Subarray Sum using Kadane's Algorithm  # Function to find the maximum subarray sum def maxSubarraySum(arr):          res = arr[0]     maxEnding = arr[0]      for i in range(1, len(arr)):                  # Find the maximum sum ending at index i by either extending          # the maximum sum subarray ending at index i - 1 or by         # starting a new subarray from index i         maxEnding = max(maxEnding + arr[i], arr[i])                  # Update res if maximum subarray sum ending at index i > res         res = max(res, maxEnding)          return res  arr = [2, 3, -8, 7, -1, 2, 3] print(maxSubarraySum(arr)) 
C#
// C# Program for Maximum Subarray Sum using Kadane's Algorithm  using System;  class GfG {          // Function to find the maximum subarray sum     static int MaxSubarraySum(int[] arr) {         int res = arr[0];         int maxEnding = arr[0];          for (int i = 1; i < arr.Length; i++) {                          // Find the maximum sum ending at index i by either extending              // the maximum sum subarray ending at index i - 1 or by             // starting a new subarray from index i             maxEnding = Math.Max(maxEnding + arr[i], arr[i]);                          // Update res if maximum subarray sum ending at index i > res             res = Math.Max(res, maxEnding);         }         return res;     }      static void Main() {         int[] arr = { 2, 3, -8, 7, -1, 2, 3 };         Console.WriteLine(MaxSubarraySum(arr));     } } 
JavaScript
// JavaScript Program for Maximum Subarray Sum using Kadane's Algorithm  // Function to find the maximum subarray sum function maxSubarraySum(arr) {     let res = arr[0];     let maxEnding = arr[0];      for (let i = 1; i < arr.length; i++) {                  // Find the maximum sum ending at index i by either extending          // the maximum sum subarray ending at index i - 1 or by         // starting a new subarray from index i         maxEnding = Math.max(maxEnding + arr[i], arr[i]);                  // Update res if maximum subarray sum ending at index i > res         res = Math.max(res, maxEnding);     }     return res; }  const arr = [2, 3, -8, 7, -1, 2, 3]; console.log(maxSubarraySum(arr)); 

Output
11

Time Complexity: O(n), since we are traversing the array only one time.
Auxiliary Space: O(1)

Related Articles:

  • Print the Maximum Sum Subarray
  • Maximum Product Subarray


Next Article
Longest subarray having maximum sum
author
kartik
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • 24*7 Innovation Labs
  • Accolite
  • Amazon
  • Amazon-Question
  • D-E-Shaw
  • FactSet
  • Flipkart
  • Hike
  • Housing.com
  • MakeMyTrip
  • MetLife
  • Microsoft
  • Morgan Stanley
  • Ola Cabs
  • Oracle
  • OYO
  • Payu
  • Samsung
  • Snapdeal
  • subarray
  • subarray-sum
  • Teradata
  • Visa
  • Visa-Question
  • VMWare
  • Walmart
  • Zoho
Practice Tags :
  • 24*7 Innovation Labs
  • Accolite
  • Amazon
  • D-E-Shaw
  • FactSet
  • Flipkart
  • Hike
  • Housing.com
  • MakeMyTrip
  • MetLife
  • Microsoft
  • Morgan Stanley
  • Ola Cabs
  • Oracle
  • Payu
  • Samsung
  • Snapdeal
  • Teradata
  • Visa
  • VMWare
  • Walmart
  • Zoho
  • Arrays
  • Dynamic Programming

Similar Reads

  • Maximum Subarray Sum using Divide and Conquer algorithm
    Given an array arr[], the task is to find the subarray that has the maximum sum and return its sum. Examples: Input: arr[] = [2, 3, -8, 7, -1, 2, 3]Output: 11Explanation: The subarray [7, -1, 2, 3] has the largest sum 11. Input: arr[] = [-2, -4]Output: –2Explanation: The subarray [-2] has the larges
    9 min read
  • Maximum Sum Alternating Subarray
    Given an array arr[] of size N, the task is to find the maximum alternating sum of a subarray possible for a given array. Alternating Subarray Sum: Considering a subarray {arr[i], arr[j]}, alternating sum of the subarray is arr[i] - arr[i + 1] + arr[i + 2] - ........ (+ / -) arr[j]. Examples: Input:
    6 min read
  • Maximum sum bitonic subarray
    Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O
    15+ min read
  • Longest subarray having maximum sum
    Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
    12 min read
  • Maximum circular subarray sum of size K
    Given an array arr of size N and an integer K, the task is to find the maximum sum subarray of size k among all contiguous sub-array (considering circular subarray also). Examples: Input: arr = {18, 4, 3, 4, 5, 6, 7, 8, 2, 10}, k = 3 Output: max circular sum = 32 start index = 9 end index = 1 Explan
    6 min read
  • Maximum Subarray Sum of Alternate Parity
    Given array A[] of size N. The Task for this problem is to find the maximum subarray (Subarrays are arrays within another array. Subarrays contain contiguous elements) sum such that adjacent elements of the subarray should have different parity. Examples: Input: A[] = {-1, 4, -1, 0, 5, -4} Output: 8
    7 min read
  • Maximum Circular Subarray Sum
    Given a circular array arr[] of size n, find the maximum possible sum of a non-empty subarray. Examples: Input: arr[] = {8, -8, 9, -9, 10, -11, 12}Output: 22Explanation: Circular Subarray {12, 8, -8, 9, -9, 10} has the maximum sum, which is 22. Input: arr[] = {10, -3, -4, 7, 6, 5, -4, -1}Output: 23
    15+ min read
  • Maximum subarray sum modulo m
    Given an array of n elements and an integer m. The task is to find the maximum value of the sum of its subarray modulo m i.e find the sum of each subarray mod m and print the maximum value of this modulo operation. Examples: Input: arr[] = {10, 7, 18}, m = 13Output: 12Explanation: All subarrays and
    7 min read
  • Maximum sum subarray after altering the array
    Given an array arr[] of size N. The task is to find the maximum subarray sum possible after performing the given operation at most once. In a single operation, you can choose any index i and either the subarray arr[0...i] or the subarray arr[i...N-1] can be reversed. Examples: Input: arr[] = {3, 4,
    15+ min read
  • CSES Solutions - Maximum Subarray Sum
    Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray. Examples: Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 9Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9. Input: N = 6, arr[] = {
    5 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