Javatpoint Logo
Javatpoint Logo

Largest Sum Contiguous Subarray (Kadane's Algorithm)

Are you ready to enter the realm of algorithms, where simplicity meets power, and the answer to a seemingly complicated problem is only around the corner? Finding the biggest sum inside a contiguous subarray of integers is a common problem in computer science and data analysis. This task, similar to looking for the right slice among a selection of pizzas, may appear difficult, but don't worry! We're going to solve the secret of Kadane's Algorithm, a wonderful approach that not only simplifies but also does it elegantly and efficiently. Join us as we dig into the enchantment of Kadane's Algorithm and see how it changes the way we approach contiguous subarray issues.

Kadane's Algorithm Approach

Kadane's Algorithm, a real game-changer in the world of contiguous subarray problems, operates with elegance and efficiency. To understand it, picture an array of numbers, some positive, some negative, and the task at hand is to discover the contiguous subarray with the largest sum. It's akin to seeking the most delicious slice of pizza in a variety of sizes and flavours.

The beauty of Kadane's Algorithm lies in its simplicity. It keeps track of two essential variables: max_ending_here and max_so_far. These variables serve as our guides through the array, helping us identify the maximum sum efficiently. Here's how it unfolds:

  1. Initialization: We begin by setting both max_ending_here and max_so_far to the value of the first element in the array. This step ensures we start with a reference point.
  2. Iteration: As we progress through the array, we repeatedly perform two key operations for each element:
    • Update max_ending_here: At each step, we decide whether it's more beneficial to start a new subarray or continue with the current one. We achieve this by comparing the current element's value with the sum of the current element and max_ending_here. Whichever is greater becomes the new max_ending_here.
    • Update max_so_far: Simultaneously, we compare max_so_far with max_ending_here and select the larger of the two. This step ensures that max_so_far always holds the maximum sum encountered so far during the iteration.
  3. Continuation: We repeat these operations for every element in the array, allowing max_so_far to evolve and capture the largest sum of any contiguous subarray.

By following these simple steps, Kadane's Algorithm ensures that at each point in the journey, we make the optimal choice, whether it involves starting anew or continuing the current subarray. This dynamic programming approach guarantees efficiency and effectiveness, even when dealing with arrays of considerable size.

Example:

input Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

We want to find the contiguous subarray with the largest sum using Kadane's Algorithm. Let's walk through it step by step:

  1. Initialization: We start by initializing two variables:
    • max_ending_here to the value of the first element, which is -2.
    • max_so_far also to -2, as it represents the maximum sum encountered so far.
  2. Iteration: Now, we iterate through the array, considering each element one by one:
    • At index 1 (Value: 1):
      • We compare the current element, 1, with the sum of the current element and max_ending_here, which is -2 + 1 = -1. Since 1 is greater than -1, we update max_ending_here to 1.
      • We also update max_so_far because it's now greater than the previous value, becoming 1.
    • At index 2 (Value: -3):
      • We compare -3 with the sum of -3 and max_ending_here, which is 1 - 3 = -2. In this case, -2 is greater than -3, so max_ending_here remains 1.
      • max_so_far doesn't change as -2 is not greater than 1.
    • At index 3 (Value: 4):
      • We compare 4 with the sum of 4 and max_ending_here, which is 1 + 4 = 5. 5 is greater than 4, so max_ending_here is updated to 5.
      • max_so_far is updated to 5 because it's now greater than the previous value.
    • Continue this process for the remaining elements:
      • At index 4 (Value: -1), max_ending_here remains 5, and max_so_far stays at 5.
      • At index 5 (Value: 2), max_ending_here becomes 7 (2 + 5), and max_so_far is updated to 7.
      • At index 6 (Value: 1), max_ending_here becomes 8 (1 + 7), and max_so_far is updated to 8.
      • At index 7 (Value: -5), max_ending_here becomes 3 (-5 + 8), and max_so_far remains 8.
      • Finally, at index 8 (Value: 4), max_ending_here becomes 7 (4 + 3), and max_so_far is updated to 8.
  3. Conclusion: After iterating through the entire array, we have our result. max_so_far holds the largest sum of a contiguous subarray, which is 8 in this case.

So, using Kadane's Algorithm, we efficiently found the largest sum (8) within the contiguous subarray [4, -1, 2, 1]. This showcases the power and simplicity of Kadane's Algorithm in solving this type of problem. It dynamically adjusts its variables to ensure the optimal choice at each step, making it a valuable tool in the programmer's toolkit.

Python Implementation

Approach 1.

Output:

Maximum contiguous sum is 7
  1. The function find_max_contiguous_subarray_sum takes an array arr as input and returns the maximum sum of a contiguous subarray.
  2. Initialize max_sum_so_far to negative infinity and current_max_sum to 0. These variables will track the maximum sum encountered so far and the current running sum, respectively.
  3. Loop throughout the elements of the input array.
  4. For each element num in the array:
    • Add num to the current_max_sum to update the running sum.
  5. Check if max_sum_so_far is less than current_max_sum. If it is, update max_sum_so_far to current_max_sum.
  6. If current_max_sum becomes negative (indicating that the current subarray doesn't contribute positively to the sum), reset current_max_sum to 0.
  7. After looping through all elements, max_sum_so_far holds the maximum sum of a contiguous subarray.
  8. Finally, print the result, which is the maximum contiguous sum.

Approach 2.

Output:

Maximum contiguous sum is 7
  1. Importing sys Library:
    The program starts by importing the sys library. The sys library provides access to some system-specific parameters and functions, including the constant sys.maxsize, which is used as an initial value for variables that need to represent negative infinity. In this case, it's used to initialize left_sum and right_sum to negative infinity.
  2. Defining the Recursive Function:
    The program defines a function named find_largest_contiguous_sum that takes an array (arr) as its input.
  3. Base Case:
    • If the length of the input array (arr) is 1 (i.e., it contains only one element), it returns that element as it represents the maximum sum possible (there's only one element).
  4. Recursive Case:
    • When the input array has more than one element, the program proceeds to the recursive case.
  5. Finding the Middle Element:
    • It calculates the index of the middle element (middle) in the array (arr).
  6. Recursive Calls:
    • The program makes two recursive calls:
      • One for the left half of the array (arr[:middle]) to find left_max.
      • Another is for the right half of the array (arr[middle:]) to find the right_max.
  7. Finding the Maximum Cross-Subarray Sum:
    • The program initializes variables left_sum and right_sum to negative infinity. These variables will be used to track the sums of subarrays from the middle element towards the left and right.
    • It also initializes current_sum to 0, which is used to calculate the sum of subarrays.
    • The program then traverses the array from the middle to the right:
      • It adds each element to current_sum.
      • Updates right_sum to be the maximum of its current value and current_sum.
    • After this, it resets current_sum to 0 and traverses the array from the middle to the left, similarly updating left_sum.
    • cross_max is calculated as the sum of the left and right subarrays that meet at the middle element.
  8. Returning the Maximum:
    • The program returns the maximum of three values: cross_max, left_max, and right_max. This represents the maximum contiguous subarray sum for the current subarray.






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