Maximum Subarray Sum

Maximum Subarray Sum

This is the Medium level question of Leetcode Link.

This question is asked in Companies like:-

bloomberg | linkedin | microsoft

Problem

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:

Input: nums = [1,-2,3,4]
Output: 7
Explanation: The subarray [3,4] has the largest sum 7.

Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

Example 3:

Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints:

  • 1 <= nums.length <= 10<sup>5</sup>

  • -10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>

Solution

In this problem, we have to find the maximum sum of the subarray. We should understand what sub-array means.

A subarray is a contiguous non-empty sequence of elements within an array.

e.g., Array = [1,-2,3,4]

Sub Array will be

[1] = 1,

[1,-2] = -1

[1,-2,3] = 2

[1,-2,3,4] = 6

[-2] = -2

[-2,3] = 1

[-2,3,4] = 5

[3] = 3

[3,4] = 7

[4] = 4

You can think of any subarray for this array, and you'll find that all are part of the above array.

Maximum sub-array sum = 7;

Brute Force Approach

A brute force solution involves generating all possible subarrays and calculating their sums. This method has a time complexity of O(n^3), making it impractical for large arrays.

int max = Integer.MIN_VALUE;
for(int i=0; i< n; i++){
    for(int j=i; j< n; j++){
        int sum = 0;
        for(int k=i; k<= j; k++){ // generate all the sub array one by one
            sum += nums[k]
        }
        max = Math.max(sum, max);
    }
}

This above code will give you the desired answer, but it will throw the TLE error.

Improved Brute Force

A slight optimization reduces the time complexity to O(n^2) by calculating subarray sums directly:

The below code is also capable of finding the maximum sub-array sum, as we are adding the number from each index of the array i=0, then 1 then 2,… to the last index so we are comparing from all the sum we are

But it's also taking the O(n^2) time complexity. Which is not good

int max = Integer.MIN_VALUE;
for(int i=0; i< n; i++){
    int sum = 0;
    for(int j=i; j< n; j++){
        sum += nums[i]
    }
    max = Math.max(sum, max);
}

Optimal Solution: Kadane's Algorithm

The most efficient solution uses Kadane's Algorithm, which operates in O(n) time and O(1) space. The algorithm iterates through the array, maintaining a running sum of the current subarray. If the sum becomes negative, it resets to zero because a negative sum would decrease the total sum of any future subarray.

As we can see in the below example:-

[1] = 1,

[1,-2] = -1,

Here -1 stored in the max,because we are trying to cover a case where sometime the entire elements can be negative, in that only one element will be able to contribute in the sum.

We are dropping the negative sum because as the sum is being negative, it'll not help in finding the maximum sub array sum. So we start finding the sum from the next element.

[3] = 2

[3,4] = 7

Hence the ans = 7, which have the following:-

Time Complexity :- O(n), and

Space Complexity :- O(1)

int max = Integer.MIN_VALUE;
int sum = 0;
for(int i=0; i< n; i++){
    sum += nums[i];
    max = Math.max(sum, max);
    if(sum <0){
        sum = 0;
    }
}

Thank you, folks, for reading till the end, if you find this solution blog helpful please like this blog.

If you have any suggestion then please drop in the comment section.

Check out my Portfolio.

Did you find this article valuable?

Support Anurag's blog by becoming a sponsor. Any amount is appreciated!