CSES Solutions - Maximum Subarray Sum
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)
Similar Reads
CSES Solutions - Maximum Subarray Sum II Given an array arr[] of N integers, your task is to find the maximum sum of values in a contiguous subarray with length between A and B. Examples: Input: N = 8, A = 1, B = 2, arr[] = {-1, 3, -2, 5, 3, -5, 2, 2}Output: 8Explanation: The subarray with maximum sum is {5, 3}, the length between 1 and 2,
12 min read
Maximum Subarray Sum in C++ In this article, we will learn how to find the maximum sum of a contiguous subarray within a given array of integers in C++ language. Finding the maximum subarray sum involves determining the contiguous subarray that has the largest sum.Example:Input:arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4}Output:6Ex
7 min read
Maximum Product Subarray in C++ In this article, we will learn how to find the maximum product of a contiguous subarray within a given array of integers. This problem is a variation of the classic "Maximum Subarray Sum" problem and presents an additional challenge because it involves both positive and negative numbers in an array.
7 min read
Minimizing Maximum Absolute Subarray Sums Given an array arr[] of size N, we can choose any real number X which when subtracted from all the elements of the array then the maximum absolute subarray sum among all the subarrays is minimum. The task is to return the minimum of maximum absolute sum among all the subarrays. Note: The answer shou
12 min read
Largest Sum Contiguous Subarray in C In this article, we will learn how to find the maximum sum of a contiguous subarray for a given array that contains both positive and negative integers in C language.Example:Input: arr = {-2, -3, 4, -1, -2, 1, 5, -3}Output: 7Explanation: The subarray {4,-1, -2, 1, 5} has the largest sum 7.Maximum su
4 min read
POTD Solutions | 23 Octâ 23 | Maximum Sum Increasing Subsequence View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up pro
4 min read