Open In App

CSES Solutions - Maximum Subarray Sum

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
3 Likes
Like
Report

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:

  • Maintain a variable sum to keep track of the running sum.
  • Maintain a variable max_sum to keep track of the maximum running sum encountered so far.
  • Iterate over the input array and add the current element to sum.
  • If the sum becomes greater than max_sum, update max_sum = sum.
  • If sum becomes negative, update sum = 0.
  • After iterating over the entire array, return max_sum as the final answer.

Below is the implementation of the algorithm:

C++
Java C# JavaScript Python3

Output
9

Time Complexity: O(N), where N is the size of the input array arr[].
Auxiliary Space: O(1)


Next Article
Practice Tags :

Similar Reads