CSES Solutions Maximum Subarray Sum (original) (raw)
Last Updated : 22 Mar, 2024
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++ `
#include <bits/stdc++.h> #define ll long long using namespace std;
// function to find the maximum subarray sum ll maxSubarraySum(ll* arr, ll N) { // variables to store the running sum and the maximum // sum ll sum = 0, max_sum = -1e9; for (int i = 0; i < N; i++) { sum += arr[i]; max_sum = max(max_sum, sum); // If we encounter a subarray with negative sum, // remove the subarray from the current sum if (sum < 0) sum = 0; } return max_sum; }
int main() { // Sample Input ll N = 8; ll arr[N] = { -1, 3, -2, 5, 3, -5, 2, 2 };
cout << maxSubarraySum(arr, N) << endl;}
Java
import java.util.*;
public class MaxSubarraySum { // Function to find the maximum subarray sum static long maxSubarraySum(long[] arr, int N) { // Variables to store the running sum and the maximum sum long sum = 0, max_sum = Long.MIN_VALUE; for (int i = 0; i < N; i++) { sum += arr[i]; max_sum = Math.max(max_sum, sum); // If we encounter a subarray with negative sum, // remove the subarray from the current sum if (sum < 0) sum = 0; } return max_sum; }
public static void main(String[] args) {
// Sample Input
int N = 8;
long[] arr = { -1, 3, -2, 5, 3, -5, 2, 2 };
System.out.println(maxSubarraySum(arr, N));
}}
// This code is contributed by akshitaguprzj3
C#
using System;
public class GFG{ // Function to find the maximum subarray sum static long MaxSubarraySum(long[] arr, int N) { // Variables to store the running sum and the maximum sum long sum = 0, max_sum = long.MinValue; for (int i = 0; i < N; i++) { sum += arr[i]; max_sum = Math.Max(max_sum, sum); // If we encounter a subarray with negative sum, // remove the subarray from the current sum if (sum < 0) sum = 0; } return max_sum; }
public static void Main() {
// Sample Input
int N = 8;
long[] arr = { -1, 3, -2, 5, 3, -5, 2, 2 };
Console.WriteLine(MaxSubarraySum(arr, N));
}}
// This code is contributed by rohit singh
JavaScript
// Function to find the maximum subarray sum function maxSubarraySum(arr) { // Variables to store the running sum and the maximum sum let sum = 0; let max_sum = -1e9;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
max_sum = Math.max(max_sum, sum);
// If we encounter a subarray with a negative sum,
// reset the sum to 0
if (sum < 0) {
sum = 0;
}
}
return max_sum;}
// Sample Input const N = 8; const arr = [-1, 3, -2, 5, 3, -5, 2, 2]; console.log(maxSubarraySum(arr));
Python3
Function to find the maximum subarray sum
def max_subarray_sum(arr): # Variables to store the running sum and the maximum sum sum_val = 0 max_sum = float('-inf') for num in arr: sum_val += num max_sum = max(max_sum, sum_val) # If we encounter a subarray with negative sum, # reset the current sum to 0 if sum_val < 0: sum_val = 0 return max_sum
Driver code
if name == "main": # Sample Input arr = [-1, 3, -2, 5, 3, -5, 2, 2] print(max_subarray_sum(arr))
`
**Time Complexity: O(N), where **N is the size of the input array **arr[].
**Auxiliary Space: O(1)