


Input: 'arr' = [1, 2, 7, -4, 3, 2, -10, 9, 1]
Output: 11
Explanation: The subarray yielding the maximum sum is [1, 2, 7, -4, 3, 2].
The first line of input contains an integer 'n', representing the array's length.
The second line of input contains 'n' single space-separated integers, denoting the elements of the array.
The output contains the maximum subarray sum.
You do not need to print anything; it has already been taken care of. Just implement the given function.
Let us check for all possible subarrays of the array. For this, we run two loops, where the outer loop points to the left boundary and the inner loop points to the outer boundary of the subarray.
Using another loop inside, find the sum of this subarray. Compare it with the maximum subarray sum obtained so far. After checking all the subarrays, simply return the maximum sum found.
Looking at the previous approach,we realize that to compute curSum[i], we only require the value of curSum[i-1]. Hence, instead of maintaining a whole array, we can simply keep track of the previous value only.
Let us start from the left of the array. We maintain an array curSum[], which keeps track of the maximum sum of the subarray ending at the index we’re at.
While traversing the array, If the value of curSum[i] becomes negative, we can simply discard this part of the array because it has a negative contribution to the subarray sum. It would be better to just drop that part and have a zero contribution rather than a negative one. Then, we can start anew with the next element. In other words, curSum[i] can be reset to 0.
The maximum value in the curSum array will be our answer.
According to the previous approach, let us fix the left boundary of the subarray in the outer loop. In the inner loop, we move our right boundary by one unit, every time.
Let’s say for a particular subarray, we have computed its sum. Now when we move the right boundary by one unit, instead of recomputing the sum for the new subarray all over again, we can simply add the value of the new element to the sum of the previous subarray.
In this way, we can reduce our time complexity by remembering the previous result.