How can you find the maximum subarray sum in an array?

Arrays Linked Lists Questions Medium



46 Short 80 Medium 67 Long Answer Questions Question Index

How can you find the maximum subarray sum in an array?

To find the maximum subarray sum in an array, you can use the Kadane's algorithm. This algorithm works by iterating through the array and keeping track of the maximum sum seen so far and the current sum.

Here is the step-by-step process to find the maximum subarray sum:

1. Initialize two variables, maxSum and currentSum, to the first element of the array.
2. Iterate through the array starting from the second element.
3. For each element, update the currentSum by adding the current element to it.
4. If the currentSum becomes negative, reset it to zero. This is because a negative sum will only decrease the overall sum of the subarray.
5. If the currentSum is greater than the maxSum, update the maxSum to the currentSum.
6. Repeat steps 3-5 until all elements of the array are processed.
7. Return the maxSum as the maximum subarray sum.

Here is an example to illustrate the process:


Given the array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

1. Initialize maxSum and currentSum to -2 (first element).
2. Iterate through the array starting from the second element (1).
3. Add 1 to the currentSum, making it -1.
4. Since the currentSum is negative, reset it to zero.
5. Update maxSum to -1 (currentSum is greater).
6. Repeat steps 3-5 for the remaining elements.
7. After processing all elements, the maxSum will be 6, which is the maximum subarray sum.

Therefore, the maximum subarray sum in the given array is 6.