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
Print subarray with maximum sum Given an array arr[], the task is to print the subarray having maximum sum.Examples:Input: arr[] = {2, 3, -8, 7, -1, 2, 3}Output: 11Explanation: The subarray {7, -1, 2, 3} has the largest sum 11.Input: arr[] = {-2, -5, 6, -2, -3, 1, 5, -6}Output: {6, -2, -3, 1, 5}Explanation: The subarray {6, -2, -3
13 min read
Find Maximum Sum Strictly Increasing Subarray Given an array of positive integers. Find the maximum sum of strictly increasing subarrays. Note that this problem is different from maximum subarray sum and maximum sum increasing subsequence problems. Examples: Input : arr[] = {1, 2, 3, 2, 5, 1, 7}Output : 8Explanation : Some Strictly increasing s
7 min read
Maximum sum bitonic subarray Given an array containing n numbers. The problem is to find the maximum sum bitonic subarray. A bitonic subarray is a subarray in which elements are first increasing and then decreasing. A strictly increasing or strictly decreasing subarray is also considered a bitonic subarray. Time Complexity of O
15+ min read