![]() |
VOOZH | about |
Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous, nonempty subarray.
Examples:
Input: N = 8, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}
Output: 9
Explanation: The subarray with maximum sum is {3, -2, 5, 3} with sum = 3 - 2 + 5 + 3 = 9.Input: N = 6, arr[] = {-10, -20, -30, -40, -50, -60}
Output: -10
Explanation: The subarray with maximum sum is {-10} with sum = -10
Approach: To solve the problem, follow the below idea:
To solve the problem, we can maintain a running sum and check whenever the running sum becomes negative, we can reset it to zero. This is because if we have a subarray with negative sum and then include more elements to it, it will only decrease the total sum. Instead, we can remove the subarray with negative sum to get a greater subarray sum. The maximum running sum will be our final answer.
Step-by-step algorithm:
Below is the implementation of the algorithm:
Below is the implementation of the algorithm:
9
Time Complexity: O(N), where N is the size of the input array arr[].
Auxiliary Space: O(1)