Javatpoint Logo
Javatpoint Logo

Kadane's Algorithm in C++

An Introduction to Kadane's Algorithm

The Kadane's Algorithm is a key tool used in data analysis and computer science to determine the highest sum of a subarray inside a given array. The data sciences, financial markets, and computer programming are just a few fields where this approach is used. In-depth discussion of Kadane's Algorithm and a thorough description of the algorithm's concepts and C++ implementation are provided in this extensive tutorial.

History of the Kadane's Algorithm

In 1984, computer scientist Jay Kadane developed the Kadane's Algorithm, which completely changed how the maximum subarray sum problem was solved. Before it was invented, brute-force methods with quadratic time complexity were used to solve this problem. Kadane's invention presented a linear-time solution and used dynamic programming ideas to keep track of the state of the system as it moved through an array. This beautiful and effective technique quickly established itself as a cornerstone of computer science education, introducing students to crucial ideas in dynamic programming. It was utilized in algorithmic contests and found uses outside of academics in a variety of industries, including bioinformatics and finance. Kadane's Algorithm is still a living example of how innovative algorithms may be used to solve complex problems.

Understanding the Problem

Let's first comprehend the issue Kadane's Algorithm attempts to solve. The goal is to identify the contiguous subarray-that is, a subarray with components that are next to one another-of an integer array that has the highest sum. It is common to refer to this subarray as the "maximum subarray."

Here's an easy illustration:

This problem must be efficiently solved in a number of applications, including stock trading strategy optimization, picture processing, and algorithm performance analysis.

Naive Approach to Implement the Kadane's Algorithm

Let's briefly examine a simplistic technique to solve this problem before discussing Kadane's Algorithm. In the brute-force approach, every potential subarray's sum is checked, and the highest sum ever discovered is recorded. Despite being simple, this method has an O(n²) time complexity, where n is the length of the input array. Because of this, it is not practicable for huge datasets.

The Kadane's Algorithm: The Idea

Finding the largest subarray sum can be more effectively accomplished using Kadane's algorithm. The algorithm's main goal is to keep track of two variables while we cycle through the array:

  1. current_max: Denotes the highest sum of a subarray that ends at the current element.
  2. global_max: Denotes the highest sum of any subarray so far encountered.

These two variables are updated each time the algorithm iterates across the array from left to right.

Step-by-step explanation of how Kadane's Algorithm works:

A popular method for determining the largest subarray sum inside a given number array is Kadane's Algorithm. It operates by quickly iterating through the array while keeping track of two significant variables, 'current_max' and 'global_max'. Let's examine Kadane's Algorithm's step-by-step operation:

  • Input: 'arr' is an array of integers.
  • Output: The maximum sum of a contiguous subarray.

Step 01 - Initialization:

  • Initialize two variables:
  • 'current_max': Denotes the maximum sum of a subarray that ends with the current element.
  • 'global_max': This value is the largest sum of any subarray so far encountered.
  • Both "current_max" and "global_max" should be set to the array's first member, as in "current_max = global_max = arr[0]".

Step 02 - Iteration:

  • Starting with the second element of the array (index 1), continue iterating over the array.
  • Perform the following for each element at index 'i':
  • Update current_max to represent the highest value obtained by summing the current element's value with current_max. By doing this, current_max is always guaranteed to be the highest sum of a subarray that ends at the current element.
  • Add the maximum of global_max and current_max to global_max. This step makes sure that global_max always reflects the highest subarray sum that has been encountered.
  • Moving from left to right, keep iterating over the full array.

Step 03 - Completion:

  • 'global_max' will hold the largest subarray sum following the completion of the iteration across the whole array.

Step 04 - Return Result:

  • As the maximum subarray sum, return the value kept in 'global_max'.

An Example Demonstrating the Implementation of the Kadane's Algorithm

Let us understand the working with an example:

Input array : [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Step 1 (Initialization):

  • current_max = -2
  • global_max = -2

Step 2 (Iteration):

  • At index 1 : 'current_max' = max(1, -2 + 1) = 1,'global_max' = max(-2, 1) = 1
  • At index 2 : 'current_max' = max(-3, 1 - 3) = -2, 'global_max' = max(1, -2) = 1.
  • At index 3 : 'current_max' = max(4, -2 + 4) = 4, 'global_max' = max(1, 4) = 4.
  • At index 4 : 'current_max' = max(-1, 4 - 1) = 3, 'global_max' = max(4, 3) = 4.
  • At index 5 : 'current_max' = max(2, 3 + 2) = 5, 'global_max' = max(4, 5) = 5.
  • At index 6 : 'current_max' = max(1, 5 + 1) = 6, 'global_max' = max(5, 6) = 6.
  • At index 7 : 'current_max' = max(-5, 6 - 5) = 1, 'global_max' = max(6, 1) = 6.
  • At index 8 : 'current_max' = max(4, 1 + 4) = 5, 'global_max' = max(6, 5) = 6.

Step 3(Completion):

  • The entire array has been traversed.

Step 4(Return Result):

  • The maximum subarray sum is stored in global_max is 6.

Output:

The maximum subarray sum is 6 corresponding to the subarray [4,-1,2,1].

Pseudocode of the Kadane's Algorithm

  1. The two variables 'current_max' and 'global_max' are used to record the highest subarray sum thus far. The value of the first member of the input array "arr" is used to initialize them both.
  2. A loop that iterates over the array's contents from the second element (index 1) to the final element ((index length(arr) - 1) is then entered by the algorithm.
  3. The method performs the following for each element at index 'i':
    • It takes the highest of two numbers to determine a probable "current_max" value:
      • 'arr[i]' is the current element.
      • the sum of the current element and the previous "current_max" value. In essence, this phase determines whether expanding the subarray that ends at the current element or beginning a new subarray with the current element will result in a greater total.
      • The maximum of the 'global_max's' current value and the newly determined 'current_max' is then used to update it. Consequently, 'global_max' will always include the highest subarray sum that has been seen up to that point.
  4. The loop keeps on until every element in the array has been handled.
  5. In order to represent the greatest subarray sum, the algorithm returns the value kept in "global_max."

Code Implementation in C++

Let us now consider the following implementation of Kadane's Algorithm in C++ Programming Language:

Explanation:

  • The code specifies a C++ program to use Kadane's Algorithm to determine the largest subarray sum.
  • It includes the iostream, vector, and essential header files.
  • 'maxSubarraySum' accepts a vector of integer references as input.
  • 'current_max' and 'global_max' are both initialized with the input vector's first element.
  • A loop that iterates across the vector beginning with element two is then initiated by the program.
  • By comparing the current element with the sum of the current element and the previous "current_max," it updates "current_max" and "global_max" inside the loop.
  • The function then returns 'global_max', which contains the largest subarray sum, after iterating over the whole vector.
  • 'maxSubarraySum' is called in the ' main function' to locate and display the largest subarray sum once a sample input vector is defined.

Output

The maximum subarray sum is 6 

Time and Space complexity Analysis of Kadane's Algorithm

Let's us now analyze the time and space complexity of the Kadane's Algorithm.

  • Time Complexity: The method performs a consistent amount of work at each step as it iterates through the input array once. The length of the input array, n, determines the time complexity, which is O(n).
  • Space Complexity: Only a fixed amount of additional space is used by the method to store the variables current_max and global_max. The space complexity is therefore O(1).

Because it can locate the largest subarray sum in linear time, Kadane's Algorithm is renowned for its effectiveness and is appropriate for huge datasets.

Some Applications of Kadane's Algorithm

The Kadane algorithm is widely used in many different fields. The following are some significant applications:

  1. Stock Trading: By determining the ideal times to purchase and sell stocks to maximize earnings, Kadane's Algorithm may be utilized in financial analysis to optimize stock trading techniques.
  2. Images Processing: Finding patterns or areas of interest within a picture is a common task for image processing systems. The Kadane algorithm may be used to effectively analyze visual data.
  3. Performance Profiling: By examining the execution timings of distinct code segments, Kadane's Algorithm may be used to pinpoint performance bottlenecks in software development.
  4. Genomic data analysis: Kadane's Algorithm is a tool used by bioinformatics researchers to analyze genomic data and pinpoint sections of interest, such as genes or regulatory components.
  5. Machine learning: Finding the most useful features is essential in machine learning applications, where Kadane's Algorithm may be used for feature selection and dimensionality reduction.

Some Optimization Techniques for Kadane's Algorithm

Despite the efficiency of Kadane's Algorithm in its simplest form, there are various modifications and optimization approaches that may be used to meet certain needs and constraints:

  1. Handling Empty Subarray: 'current_max' and 'global_max' can be initialized to zero initially to address the circumstance when the issue allows empty subarrays (subarrays with no elements).
  2. Tracking Subarray indices: You may modify the technique to keep track of the starting and ending indices of the largest subarray while you cycle over the array if you need to determine these indices.
  3. Divide and Conquer: To effectively locate the largest subarray for really big datasets, you can investigate divide-and-conquer methods.

Some Advantages of the Kadane's Algorithm

  1. Efficiency: Kadane's Algorithm has efficiency as one of its main benefits. When n is the length of the input array, it can discover the largest subarray sum with a linear time complexity of O(n). Because of its efficiency, it can handle processing big datasets, making it a useful tool for many different applications.
  2. Simplicity: It is reasonably easy to comprehend and apply Kadane's algorithm. Its core concept of keeping two variables (current_max and global_max) constant while iterating across the array is simple and straightforward. It is approachable for both inexperienced and seasoned programmers due to its simplicity.
  3. Optimal Substructure: The recursive form of the method is in good agreement with the fundamentals of dynamic programming. Finding the largest subarray sum is broken down into smaller, easier-to-manage subproblems, making it simple to understand and adapt to various problem-solving contexts.
  4. Memory Efficiency: Since just a small amount of extra memory is needed to hold the two variables current_max and global_max, Kadane's algorithm is memory-efficient. This tiny memory footprint is particularly helpful when dealing with huge datasets or in contexts with limited resources.
  5. Versatility: Despite the fact that Kadane's Algorithm is intended to determine the largest subarray sum, it may be modified to solve a variety of different issues. For instance, by significantly altering the technique, you may locate the maximum subarray's beginning and ending indices or keep track of more data as required.
  6. Applications: Numerous real-world uses for the algorithm exist in numerous industries. It is frequently employed in a number of fields, including biology to analyze genetic data and finance to improve stock trading methods and detect performance bottlenecks. It is an excellent tool for solving problems because of its effectiveness and adaptability.

Some Disadvantages of the Kadane's Algorithm

  1. Limited to Contiguous subarray: The fact that Kadane's algorithm is built to discover the largest sum of contiguous subarrays is a key constraint. It might not be appropriate for issues involving non-contiguous subarrays or more intricate subarray selection patterns.
  2. Negative only Arrays: Kadane's Algorithm might not provide the anticipated outcomes if the input array is completely made up of negative values. The largest negative number will be returned, which might not exactly reflect the goal of the issue. In these circumstances, special management is necessary.
  3. Single Pass Algorithm: Although its single-pass design reduces time complexity, it might be a drawback if new needs call for returning to the array more than once. Alternative algorithms or changes could be required in such circumstances.
  4. No information on Subarray Indices: The greatest subarray sum is provided by Kadane's algorithm, but it does not immediately produce data on the starting and ending indices of the subarray that reaches this maximum. If this data is necessary, more logic must be introduced, perhaps making the code more complicated.
  5. Special Cases and Edge Cases: While Kadane's Algorithm is quite effective in the majority of situations, there are some edge circumstances that need special attention, such as when the input array is empty or when all components are negative. The implementation may be hampered by certain edge cases.

The Conclusion

An effective method for resolving the maximum subarray sum problem is Kadane's Algorithm. The maximum subarray sum may be found in linear time by retaining two variables (current_max and global_max) as we cycle over the array, making it appropriate for a variety of applications.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA