Kadane's Algorithm | Maximum subarray sum - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, we will see how to solve the maximum sub array sum problem efficiently using the Kadane’s Algorithm.
What is the maximum subarray sum problem? Say, you’re given an array of integers, of size n, and you’re asked to find the contiguous sub array with maximum sum, how will you do that? More specifically, if you’re asked to find the sum of such contiguous subarray, how will you approach the problem?
The brute force solution involves finding all possible contiguous sub arrays and finding the sum, to find the maximum possible sum. For this, we need to run two loops, one iterating over the array elements to fix the leftmost element of the subarray, and the other loop keeps iterating on the right of this chosen element to fix the rightmost element of the subarray.
What is the time complexity of this approach? Since we’re running two for loops, it’ll take O(n2) time complexity.
Can this be improved? Can this be solved in a single pass?
Iterate over the array and keep track of two variables max_so_far and max_ending_here.
Initially, both max_so_far and max_ending_here are initialized to zero.
At index i, max_ending_here computes the subarray with largest sum ending at i, and, max_so_far computes the subarray with the largest sum anywhere in A[0..i].
Keep updating the two variables at every iteration, and at the end of the pass, max_so_far holds the maximum subarray sum.
The pseudo code for implementing the above approach :
     Initialize : 
     max_so_far = 0 
     max_ending_here = 0 
     Loop over the elements of the array : 
     At index i, of the array 
      max_ending_here = max_ending_here+arr[i] 
      if(max_ending_here < 0) 
        max_ending_here = 0 
      if(max_ending_here > max_so_far) 
        max_so_far = max_ending_here 
     return max_so_far


def maxSubArraySum(a,size):
    (max_so_far, max_ending_here)=(0,0)
    for num in a:
        max_ending_here = max_ending_here+num
        if(max_ending_here > max_so_far):
            max_so_far = max_ending_here
        if(max_ending_here < 0):
            max_ending_here=0
    return max_so_far


if __name__ == "__main__":
  arr = [-2,1,-3,4,-1,2,1,-5,4]
  res = maxSubArraySum(arr,9)
  print("Output : ",res)
Output:  6

import java.util.*;
import java.io.*;

public class kadanes
{
  public static void main(String[] args)
  {
    int arr[] = {-2,1,-3,4,-1,2,1,-5,4};
    int n = arr.length;
        	int max_so_far=0, max_ending_here=0;
        	for(int i=0; i<n; i++)
        	{
            		max_ending_here = max_ending_here+arr[i];
            		if(max_ending_here > max_so_far)
                		max_so_far = max_ending_here;
            		if(max_ending_here < 0)
                		max_ending_here = 0;
        	}

    System.out.println(max_so_far);
        
  }
}
Since this approach works in a single pass, the time complexity is O(n). It doesn’t utilize any extra memory, and hence, the space complexity is constant, i.e., O(1).
This algorithm uses “optimal substructures” i.e., the maximum subarray ending at each position is computed from the maximum subarray ending at the previous position, and hence, this approach is a simple application of dynamic programming.
More on Maximum Sub-Array Problem
Three way Partitioning Problem

How to implement Counting Sort Algorithm Python
How to find a missing number in an array ?
Python – Three way partitioning of an Array Example
C Program – Print the sum of digits of given number
How to Rotate an Array to Left direction based on user input ?
Java program to find sum of digits
What is an Algorithm ?
C Program – Sum of digits of given number till single digit
C Program to add elements of an array
Arithmetic Operations on NumPy Arrays
C Program – Reverse the Elements of an Array
Binary Search using Java
Different ways to use Lambdas in Python
Organization of data In Data Structures
Difference between b++ and b=b+1

How to implement Counting Sort Algorithm Python
How to find a missing number in an array ?
Python – Three way partitioning of an Array Example
C Program – Print the sum of digits of given number
How to Rotate an Array to Left direction based on user input ?
Java program to find sum of digits
What is an Algorithm ?
C Program – Sum of digits of given number till single digit
C Program to add elements of an array
Arithmetic Operations on NumPy Arrays
C Program – Reverse the Elements of an Array
Binary Search using Java
Different ways to use Lambdas in Python
Organization of data In Data Structures
Difference between b++ and b=b+1
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list
 Install Java on Mac OS
 Install AWS CLI on Windows
 Install Minikube on Windows
 Install Docker Toolbox on Windows
 Install SOAPUI on Windows
 Install Gradle on Windows
 Install RabbitMQ on Windows
 Install PuTTY on windows
 Install Mysql on Windows
 Install Hibernate Tools in Eclipse
 Install Elasticsearch on Windows
 Install Maven on Windows
 Install Maven on Ubuntu
 Install Maven on Windows Command
 Add OJDBC jar to Maven Repository
 Install Ant on Windows
 Install RabbitMQ on Windows
 Install Apache Kafka on Ubuntu
 Install Apache Kafka on Windows
 Java8 – Install Windows
 Java8 – foreach
 Java8 – forEach with index
 Java8 – Stream Filter Objects
 Java8 – Comparator Userdefined
 Java8 – GroupingBy
 Java8 – SummingInt
 Java8 – walk ReadFiles
 Java8 – JAVA_HOME on Windows
 Howto – Install Java on Mac OS
 Howto – Convert Iterable to Stream
 Howto – Get common elements from two Lists
 Howto – Convert List to String
 Howto – Concatenate Arrays using Stream
 Howto – Remove duplicates from List
 Howto – Filter null values from Stream
 Howto – Convert List to Map
 Howto – Convert Stream to List
 Howto – Sort a Map
 Howto – Filter a Map
 Howto – Get Current UTC Time
 Howto – Verify an Array contains a specific value
 Howto – Convert ArrayList to Array
 Howto – Read File Line By Line
 Howto – Convert Date to LocalDate
 Howto – Merge Streams
 Howto – Resolve NullPointerException in toMap
 Howto -Get Stream count
 Howto – Get Min and Max values in a Stream
 Howto – Convert InputStream to String