Maximum Subarray Sum in a given Range
Last Updated :
14 Mar, 2023
Given an array of n numbers, the task is to answer the following queries:
maximumSubarraySum(start, end) : Find the maximum
subarray sum in the range from array index 'start'
to 'end'.
Also see : Range Query With Update Required
Examples:
Input : arr[] = {1, 3, -4, 5, -2}
Query 1: start = 0, end = 4
Query 2: start = 0, end = 2
Output : 5
4
Explanation:
For Query 1, [1, 3, -4, 5] or ( [5] )
represent the maximum sum sub arrays
with sum = 5.
For Query 2, [1, 3] represents the
maximum sum subarray in the query range
with sum = 4
Segment Trees can be used to solve this problem. Here, we need to keep information regarding various cumulative sums. At every Node we store the following:
- Maximum Prefix Sum,
- Maximum Suffix Sum,
- Total Sum,
- Maximum Subarray Sum
A classical Segment Tree with each Node storing the above information should be enough to answer each query. The only focus here is on how the left and the right Nodes of the tree are merged together. Now, we will discuss how each of the information is constructed in each of the segment tree Nodes using the information of its left and right child.
Constructing the Maximum Prefix Sum using Left and Right child
There can be two cases for maximum prefix sum of a Node:
- The maximum prefix sum occurs in the left child,

In this Case,
Maximum Prefix Sum = Maximum Prefix Sum of Left Child
- The maximum prefix sum contains every array element of the left child and the elements contributing to the maximum prefix sum of the right child,

In this Case,
Maximum Prefix Sum = Total Sum of Left Child +
Maximum Prefix Sum of Right Child
Constructing the Maximum Suffix Sum using Left and Right child
There can be two cases for maximum suffix sum of a Node:
- The maximum suffix sum occurs in the right child,

In this Case,
Maximum Suffix Sum = Maximum Suffix Sum of Right Child
- The maximum suffix sum contains every array element of the Right child and the elements contributing to the maximum suffix sum of the left child,
In this Case,
Maximum Suffix Sum = Total Sum of Right Child +
Maximum Suffix Sum of Left Child
Constructing the Maximum Subarray Sum using Left and Right child
There can be three cases for the maximum sub-array sum of a Node:
- The maximum sub-array sum occurs in the left child,
In this Case,
Maximum Sub-array Sum = Maximum Subarray Sum of Left Child
- The maximum sub-array sum occurs in the right child,

In this Case,
Maximum Sub-array Sum = Maximum Subarray Sum of Right Child
- The maximum subarray sum, contains array elements of the right child contributing to the maximum prefix sum of the right child, and the array elements of the Left child contributing to the maximum suffix sum of the left child,

In this Case,
Maximum Subarray Sum = Maximum Prefix Sum of Right Child
+
Maximum Suffix Sum of Left Child
Implementation:
CPP
// C++ Program to Implement Maximum Sub-Array Sum in a range
#include <bits/stdc++.h>
using namespace std;
#define inf 0x3f3f
/* Node of the segment tree consisting of:
1. Maximum Prefix Sum,
2. Maximum Suffix Sum,
3. Total Sum,
4. Maximum Sub-Array Sum */
struct Node {
int maxPrefixSum;
int maxSuffixSum;
int totalSum;
int maxSubarraySum;
Node()
{
maxPrefixSum = maxSuffixSum = maxSubarraySum = -inf;
totalSum = -inf;
}
};
// Returns Parent Node after merging its left and right child
Node merge(Node leftChild, Node rightChild)
{
Node parentNode;
parentNode.maxPrefixSum = max(leftChild.maxPrefixSum,
leftChild.totalSum +
rightChild.maxPrefixSum);
parentNode.maxSuffixSum = max(rightChild.maxSuffixSum,
rightChild.totalSum +
leftChild.maxSuffixSum);
parentNode.totalSum = leftChild.totalSum +
rightChild.totalSum;
parentNode.maxSubarraySum = max({leftChild.maxSubarraySum,
rightChild.maxSubarraySum,
leftChild.maxSuffixSum +
rightChild.maxPrefixSum});
return parentNode;
}
// Builds the Segment tree recursively
void constructTreeUtil(Node* tree, int arr[], int start,
int end, int index)
{
/* Leaf Node */
if (start == end) {
// single element is covered under this range
tree[index].totalSum = arr[start];
tree[index].maxSuffixSum = arr[start];
tree[index].maxPrefixSum = arr[start];
tree[index].maxSubarraySum = arr[start];
return;
}
// Recursively Build left and right children
int mid = (start + end) / 2;
constructTreeUtil(tree, arr, start, mid, 2 * index);
constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1);
// Merge left and right child into the Parent Node
tree[index] = merge(tree[2 * index], tree[2 * index + 1]);
}
/* Function to construct segment tree from given array.
This function allocates memory for segment tree and
calls constructTreeUtil() to fill the allocated
memory */
Node* constructTree(int arr[], int n)
{
// Allocate memory for segment tree
int x = (int)(ceil(log2(n))); // Height of the tree
// Maximum size of segment tree
int max_size = 2 * (int)pow(2, x) - 1;
Node* tree = new Node[max_size];
// Fill the allocated memory tree
constructTreeUtil(tree, arr, 0, n - 1, 1);
// Return the constructed segment tree
return tree;
}
/* A Recursive function to get the desired
Maximum Sum Sub-Array,
The following are parameters of the function-
tree --> Pointer to segment tree
index --> Index of the segment tree Node
ss & se --> Starting and ending indexes of the
segment represented by
current Node, i.e., tree[index]
qs & qe --> Starting and ending indexes of query range */
Node queryUtil(Node* tree, int ss, int se, int qs,
int qe, int index)
{
// No overlap
if (ss > qe || se < qs) {
// returns a Node for out of bounds condition
Node nullNode;
return nullNode;
}
// Complete overlap
if (ss >= qs && se <= qe) {
return tree[index];
}
// Partial Overlap Merge results of Left
// and Right subtrees
int mid = (ss + se) / 2;
Node left = queryUtil(tree, ss, mid, qs, qe,
2 * index);
Node right = queryUtil(tree, mid + 1, se, qs,
qe, 2 * index + 1);
// merge left and right subtree query results
Node res = merge(left, right);
return res;
}
/* Returns the Maximum Subarray Sum between start and end
It mainly uses queryUtil(). */
int query(Node* tree, int start, int end, int n)
{
Node res = queryUtil(tree, 0, n - 1, start, end, 1);
return res.maxSubarraySum;
}
int main()
{
int arr[] = { 1, 3, -4, 5, -2 };
int n = sizeof(arr) / sizeof(arr[0]);
// Construct Segment Tree
Node* Tree = constructTree(arr, n);
int start, end, maxSubarraySum;
// Answering query 1:
start = 0;
end = 4;
maxSubarraySum = query(Tree, start, end, n);
cout << "Maximum Sub-Array Sum between "
<< start << " and " << end
<< " = " << maxSubarraySum << "\n";
// Answering query 2:
start = 0;
end = 2;
maxSubarraySum = query(Tree, start, end, n);
cout << "Maximum Sub-Array Sum between "
<< start << " and " << end
<< " = " << maxSubarraySum << "\n";
return 0;
}
Java
// Java Program to Implement Maximum Sub-Array Sum in a
// range
import java.io.*;
import java.util.*;
/* Node of the segment tree consisting of:
1. Maximum Prefix Sum,
2. Maximum Suffix Sum,
3. Total Sum,
4. Maximum Sub-Array Sum */
class Node {
int maxPrefixSum;
int maxSuffixSum;
int totalSum;
int maxSubarraySum;
Node()
{
maxPrefixSum = maxSuffixSum = maxSubarraySum
= Integer.MIN_VALUE;
totalSum = Integer.MIN_VALUE;
}
}
class GFG {
static final int inf = 0x3f3f;
// Returns Parent Node after merging its left and right
// child
static Node merge(Node leftChild, Node rightChild)
{
Node parentNode = new Node();
parentNode.maxPrefixSum = Math.max(
leftChild.maxPrefixSum,
leftChild.totalSum + rightChild.maxPrefixSum);
parentNode.maxSuffixSum = Math.max(
rightChild.maxSuffixSum,
rightChild.totalSum + leftChild.maxSuffixSum);
parentNode.totalSum
= leftChild.totalSum + rightChild.totalSum;
parentNode.maxSubarraySum
= Math.max(Math.max(leftChild.maxSubarraySum,
rightChild.maxSubarraySum),
leftChild.maxSuffixSum
+ rightChild.maxPrefixSum);
return parentNode;
}
// Builds the Segment tree recursively
static void constructTreeUtil(Node[] tree, int[] arr,
int start, int end,
int index)
{
/* Leaf Node */
if (start == end) {
// single element is covered under this range
tree[index].totalSum = arr[start];
tree[index].maxSuffixSum = arr[start];
tree[index].maxPrefixSum = arr[start];
tree[index].maxSubarraySum = arr[start];
return;
}
// Recursively Build left and right children
int mid = (start + end) / 2;
constructTreeUtil(tree, arr, start, mid, 2 * index);
constructTreeUtil(tree, arr, mid + 1, end,
2 * index + 1);
// Merge left and right child into the Parent Node
tree[index]
= merge(tree[2 * index], tree[2 * index + 1]);
}
/* Function to construct segment tree from given array.
* This function allocates memory for segment tree and
* calls constructTreeUtil() to fill the allocated
* memory */
static Node[] constructTree(int[] arr, int n)
{
// Allocate memory for segment tree
int x = (int)(Math.ceil(
Math.log(n)
/ Math.log(2))); // Height of the tree
// Maximum size of segment tree
int max_size = 2 * (int)Math.pow(2, x) - 1;
Node[] tree = new Node[max_size];
for (int i = 0; i < max_size; i++)
tree[i] = new Node();
// Fill the allocated memory tree
constructTreeUtil(tree, arr, 0, n - 1, 1);
// Return the constructed segment tree
return tree;
}
/* A Recursive function to get the desired
Maximum Sum Sub-Array,
The following are parameters of the function-
tree --> Pointer to segment tree
index --> Index of the segment tree Node
ss & se --> Starting and ending indexes of the
segment represented by
current Node, i.e., tree[index]
qs & qe --> Starting and ending indexes of query range */
static Node queryUtil(Node[] tree, int ss, int se,
int qs, int qe, int index)
{
// No overlap
if (ss > qe || se < qs) {
// returns a Node for out of bounds condition
Node nullNode = new Node();
return nullNode;
}
// Complete overlap
if (ss >= qs && se <= qe) {
return tree[index];
}
// Partial Overlap Merge results of Left and Right
// subtrees
int mid = (ss + se) / 2;
Node left
= queryUtil(tree, ss, mid, qs, qe, 2 * index);
Node right = queryUtil(tree, mid + 1, se, qs, qe,
2 * index + 1);
// merge left and right subtree query results
Node res = merge(left, right);
return res;
}
/* Returns the Maximum Subarray Sum between start and
* end It mainly uses queryUtil(). */
static int query(Node[] tree, int start, int end, int n)
{
Node res = queryUtil(tree, 0, n - 1, start, end, 1);
return res.maxSubarraySum;
}
public static void main(String[] args)
{
int[] arr = { 1, 3, -4, 5, -2 };
int n = arr.length;
// Construct Segment Tree
Node[] Tree = constructTree(arr, n);
int start, end, maxSubarraySum;
// Answering query 1:
start = 0;
end = 4;
maxSubarraySum = query(Tree, start, end, n);
System.out.println("Maximum Sub-Array Sum between "
+ start + " and " + end + " = "
+ maxSubarraySum);
// Answering query 2:
start = 0;
end = 2;
maxSubarraySum = query(Tree, start, end, n);
System.out.println("Maximum Sub-Array Sum between "
+ start + " and " + end + " = "
+ maxSubarraySum);
}
}
// This code is contributed by sankar.
Python3
# Python Program to Implement Maximum Sub-Array Sum in a range
import math
# Node of the segment tree consisting of:
# 1. Maximum Prefix Sum,
# 2. Maximum Suffix Sum,
# 3. Total Sum,
# 4. Maximum Sub-Array Sum
class Node:
def __init__(self):
self.maxPrefixSum = float("-inf")
self.maxSuffixSum = float("-inf")
self.totalSum = float("-inf")
self.maxSubarraySum = float("-inf")
# Returns Parent Node after merging its left and right child
def merge(leftChild, rightChild):
parentNode = Node()
parentNode.maxPrefixSum = max(leftChild.maxPrefixSum, leftChild.totalSum + rightChild.maxPrefixSum)
parentNode.maxSuffixSum = max(rightChild.maxSuffixSum, rightChild.totalSum + leftChild.maxSuffixSum)
parentNode.totalSum = leftChild.totalSum + rightChild.totalSum
parentNode.maxSubarraySum = max(leftChild.maxSubarraySum, rightChild.maxSubarraySum, leftChild.maxSuffixSum + rightChild.maxPrefixSum)
return parentNode
# Builds the Segment tree recursively
def constructTreeUtil(tree, arr, start, end, index):
# Leaf Node
if start == end:
# single element is covered under this range
tree[index] = Node()
tree[index].totalSum = arr[start]
tree[index].maxSuffixSum = arr[start]
tree[index].maxPrefixSum = arr[start]
tree[index].maxSubarraySum = arr[start]
return
# Recursively Build left and right children
mid = (start + end) // 2
constructTreeUtil(tree, arr, start, mid, 2 * index)
constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1)
# Merge left and right child into the Parent Node
tree[index] = merge(tree[2 * index], tree[2 * index + 1])
# Function to construct segment tree from given array.
# This function allocates memory for segment tree and
# calls constructTreeUtil() to fill the allocated
# memory
def constructTree(arr, n):
# Allocate memory for segment tree
x = int(math.ceil(math.log2(n))) # Height of the tree
# Maximum size of segment tree
max_size = 2 * int(math.pow(2, x)) - 1
tree = [Node() for i in range(max_size)]
# Fill the allocated memory tree
constructTreeUtil(tree, arr, 0, n - 1, 1)
# Return the constructed segment tree
return tree
# A Recursive function to get the desired
# Maximum Sum Sub-Array,
# The following are parameters of the function-
# tree --> Pointer to segment tree
# index --> Index of the segment tree Node
# ss & se --> Starting and ending indexes of the
# segment represented by
# current Node, i.e., tree[index]
# qs & qe --> Starting and ending indexes of query range
def queryUtil(tree, ss, se, qs, qe, index):
# No overlap
if ss > qe or se < qs:
# returns a Node for out of bounds condition
return Node()
# Complete overlap
if ss >= qs and se <= qe:
return tree[index]
# Partial Overlap
mid = (ss + se) // 2
left = queryUtil(tree, ss, mid, qs, qe, 2 * index)
right = queryUtil(tree, mid + 1, se, qs, qe, 2 * index + 1)
return merge(left, right)
# Function to get the desired Maximum Sum Sub-Array
def query(tree, n, qs, qe):
# pass the index of the root node
return queryUtil(tree, 0, n - 1, qs, qe, 1)
# Driver code
if __name__ == "__main__":
# test array
arr = [1, 3, -4, 5, -2]
n = len(arr)
# Construct Segment Tree
Tree = constructTree(arr, n)
# Answering query 1:
start = 0
end = 4
maxSubarraySum = query(Tree, n, start, end).maxSubarraySum
print("Maximum Sub-Array Sum between", start, "and", end, "=", maxSubarraySum)
# Answering query 2:
start = 0
end = 2
maxSubarraySum = query(Tree, n, start, end).maxSubarraySum
print("Maximum Sub-Array Sum between", start, "and", end, "=", maxSubarraySum)
# This code is contributed by Vikram_Shirsat
C#
// C# Program to Implement Maximum Sub-Array Sum in a range
using System;
/* Node of the segment tree consisting of:
1. Maximum Prefix Sum,
2. Maximum Suffix Sum,
3. Total Sum,
4. Maximum Sub-Array Sum
*/
public class Node {
public int maxPrefixSum;
public int maxSuffixSum;
public int totalSum;
public int maxSubarraySum;
public Node() {
maxPrefixSum = maxSuffixSum = maxSubarraySum = int.MinValue;
totalSum = int.MinValue;
}
}
public class GFG {
static readonly int inf = 0x3f3f;
// Returns Parent Node after merging its left and right child
static Node merge(Node leftChild, Node rightChild) {
Node parentNode = new Node();
parentNode.maxPrefixSum = Math.Max(
leftChild.maxPrefixSum,
leftChild.totalSum + rightChild.maxPrefixSum
);
parentNode.maxSuffixSum = Math.Max(
rightChild.maxSuffixSum,
rightChild.totalSum + leftChild.maxSuffixSum
);
parentNode.totalSum = leftChild.totalSum + rightChild.totalSum;
parentNode.maxSubarraySum = Math.Max(
Math.Max(leftChild.maxSubarraySum, rightChild.maxSubarraySum),
leftChild.maxSuffixSum + rightChild.maxPrefixSum
);
return parentNode;
}
// Builds the Segment tree recursively
static void constructTreeUtil(Node[] tree, int[] arr, int start, int end, int index) {
/* Leaf Node */
if (start == end) {
// single element is covered under this range
tree[index].totalSum = arr[start];
tree[index].maxSuffixSum = arr[start];
tree[index].maxPrefixSum = arr[start];
tree[index].maxSubarraySum = arr[start];
return;
}
// Recursively Build left and right children
int mid = (start + end) / 2;
constructTreeUtil(tree, arr, start, mid, 2 * index);
constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1);
// Merge left and right child into the Parent Node
tree[index] = merge(tree[2 * index], tree[2 * index + 1]);
}
/* Function to construct segment tree from given array.
* This function allocates memory for segment tree and
* calls constructTreeUtil() to fill the allocated
* memory */
static Node[] constructTree(int[] arr, int n) {
// Allocate memory for segment tree
int x = (int)(Math.Ceiling(Math.Log(n) / Math.Log(2)));
// Maximum size of segment tree
int max_size = 2 * (int)Math.Pow(2, x) - 1;
Node[] tree = new Node[max_size];
for (int i = 0; i < max_size; i++)
tree[i] = new Node();
// Fill the allocated memory tree
constructTreeUtil(tree, arr, 0, n - 1, 1);
// Return the constructed segment tree
return tree;
}
/* A Recursive function to get the desired
Maximum Sum Sub-Array,
The following are parameters of the function-
tree --> Pointer to segment tree
index --> Index of the segment tree Node
ss & se --> Starting and ending indexes of the
segment represented by
current Node, i.e., tree[index]
qs & qe --> Starting and ending indexes of query range */
static Node queryUtil(Node[] tree, int ss, int se, int qs, int qe, int index) {
if (ss > qe || se < qs) {
Node nullNode = new Node();
return nullNode;
}
if (ss >= qs && se <= qe) {
return tree[index];
}
int mid = (ss + se) / 2;
Node left = queryUtil(tree, ss, mid, qs, qe, 2 * index);
Node right = queryUtil(tree, mid + 1, se, qs, qe, 2 * index + 1);
Node res = merge(left, right);
return res;
}
/* Returns the Maximum Subarray Sum between start and
* end It mainly uses queryUtil(). */
static int query(Node[] tree, int start, int end, int n) {
Node res = queryUtil(tree, 0, n - 1, start, end, 1);
return res.maxSubarraySum;
}
public static void Main(string[] args) {
int[] arr = { 1, 3, -4, 5, -2 };
int n = arr.Length;
Node[] Tree = constructTree(arr, n);
int start, end, maxSubarraySum;
// Answering query 1:
start = 0;
end = 4;
maxSubarraySum = query(Tree, start, end, n);
Console.WriteLine("Maximum Sub-Array Sum between " + start + " and " + end + " = " + maxSubarraySum);
// Answering query 2:
start = 0;
end = 2;
maxSubarraySum = query(Tree, start, end, n);
Console.WriteLine("Maximum Sub-Array Sum between " + start + " and " + end + " = " + maxSubarraySum);
}
}
JavaScript
// JavaScript Program to Implement Maximum Sub-Array Sum in a range
/* Node of the segment tree consisting of:
1. Maximum Prefix Sum,
2. Maximum Suffix Sum,
3. Total Sum,
4. Maximum Sub-Array Sum */
class Node {
constructor() {
this.maxPrefixSum = -Infinity;
this.maxSuffixSum = -Infinity;
this.totalSum = -Infinity;
this.maxSubarraySum = -Infinity;
}
}
const inf = 0x3f3f;
// Returns Parent Node after merging its left and right child
function merge(leftChild, rightChild) {
const parentNode = new Node();
parentNode.maxPrefixSum = Math.max(
leftChild.maxPrefixSum,
leftChild.totalSum + rightChild.maxPrefixSum
);
parentNode.maxSuffixSum = Math.max(
rightChild.maxSuffixSum,
rightChild.totalSum + leftChild.maxSuffixSum
);
parentNode.totalSum = leftChild.totalSum + rightChild.totalSum;
parentNode.maxSubarraySum = Math.max(
Math.max(
leftChild.maxSubarraySum,
rightChild.maxSubarraySum
),
leftChild.maxSuffixSum + rightChild.maxPrefixSum
);
return parentNode;
}
// Builds the Segment tree recursively
function constructTreeUtil(tree, arr, start, end, index) {
/* Leaf Node */
if (start === end) {
// single element is covered under this range
tree[index].totalSum = arr[start];
tree[index].maxSuffixSum = arr[start];
tree[index].maxPrefixSum = arr[start];
tree[index].maxSubarraySum = arr[start];
return;
}
// Recursively Build left and right children
const mid = Math.floor((start + end) / 2);
constructTreeUtil(tree, arr, start, mid, 2 * index);
constructTreeUtil(tree, arr, mid + 1, end, 2 * index + 1);
// Merge left and right child into the Parent Node
tree[index] = merge(tree[2 * index], tree[2 * index + 1]);
}
/* Function to construct segment tree from given array.
* This function allocates memory for segment tree and
* calls constructTreeUtil() to fill the allocated
* memory */
function constructTree(arr, n) {
// Allocate memory for segment tree
const x = Math.ceil(Math.log2(n)); // Height of the tree
// Maximum size of segment tree
const max_size = 2 * Math.pow(2, x) - 1;
const tree = new Array(max_size);
for (let i = 0; i < max_size; i++)
tree[i] = new Node();
// Fill the allocated memory tree
constructTreeUtil(tree, arr, 0, n - 1, 1);
// Return the constructed segment tree
return tree;
}
/* A Recursive function to get the desired Maximum Sum Sub-Array,
The following are parameters of the function-
tree --> Pointer to segment tree
index --> Index of the segment tree Node
ss & se --> Starting and ending indexes of the
segment represented by
current Node, i.e., tree[index]
qs & qe --> Starting and ending indexes of query range */
function queryUtil(tree, ss, se, qs, qe, index) {
// No overlap
if (ss > qe || se < qs) {
// returns a Node for out of bounds condition
const nullNode = new Node();
return nullNode;
}
// Complete overlap
if (qs <= ss && qe >= se) {
return tree[index];
}
// Partial Overlap
const mid = Math.floor((ss + se) / 2);
const leftChild = queryUtil(tree, ss, mid, qs, qe, 2 * index);
const rightChild = queryUtil(tree, mid + 1, se, qs, qe, 2 * index + 1);
return merge(leftChild, rightChild);
}
/* Function to answer the queries */
function query(tree, start, end, n) {
const res = queryUtil(tree, 0, n - 1, start, end, 1);
return res.maxSubarraySum;
}
/* Main Function */
const arr = [1, 3, -4, 5, -2];
const n = arr.length;
// Construct Segment Tree
const Tree = constructTree(arr, n);
let start, end, maxSubarraySum;
// Answering query 1:
start = 0;
end = 4;
maxSubarraySum = query(Tree, start, end, n);
console.log(`Maximum Sub-Array Sum between ${start} and ${end} = ${maxSubarraySum} <br>`);
// Answering query 2:
start = 0;
end = 2;
maxSubarraySum = query(Tree, start, end, n);
console.log(`Maximum Sub-Array Sum between ${start} and ${end} = ${maxSubarraySum}`);
// This code is contributed by karthik.
Output: Maximum Sub-Array Sum between 0 and 4 = 5
Maximum Sub-Array Sum between 0 and 2 = 4
Time Complexity: O(logn) for each query.
Similar Reads
Find maximum sum by replacing the Subarray in given range
Given an array arr[], the task is to find the maximum sum possible such that any subarray of the indices from [l, r] i.e all subarray elements from arr[l] to arr[r] can be replaced with |arr[l] - arr[r]| any number of times. Examples: Input: arr[] = { 9, 1}Output: 16Explanation: The subarray [l, r]
9 min read
Maximum Sum Alternating Subarray
Given an array arr[] of size N, the task is to find the maximum alternating sum of a subarray possible for a given array. Alternating Subarray Sum: Considering a subarray {arr[i], arr[j]}, alternating sum of the subarray is arr[i] - arr[i + 1] + arr[i + 2] - ........ (+ / -) arr[j]. Examples: Input:
6 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
Maximum sum subarray of size range [L, R]
Given an integer array arr[] of size N and two integer L and R. The task is to find the maximum sum subarray of size between L and R (both inclusive). Example: Input: arr[] = {1, 2, 2, 1}, L = 1, R = 3 Output: 5 Explanation: Subarray of size 1 are {1}, {2}, {2}, {1} and maximum sum subarray = 2 for
8 min read
Longest subarray having maximum sum
Given an array arr[] containing n integers. The problem is to find the length of the subarray having maximum sum. If there exists two or more subarrays with maximum sum then print the length of the longest subarray.Examples: Input : arr[] = {5, -2, -1, 3, -4}Output : 4There are two subarrays with ma
12 min read
Count subarrays with max values in given range
Given an integer array arr[] and two integers l and r. The task is to find the count of subarrays where the maximum element in that subarray is in range [l, r]. In other words, the max element is at least l and at most r.Examples: Input: arr[] = [1, 2, 3, 4, 5], l = 2, r = 5Output: 11Explanation: Va
10 min read
Maximum Subarray Sum - Kadane's Algorithm
Given an array arr[], the task is to find the subarray that has the maximum sum and return its 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, -4}Output: -2Explanation: The subarray {-2} has the largest s
9 min read
Maximum sum two non-overlapping subarrays of given size
Given an array, we need to find two subarrays with a specific length K such that sum of these subarrays is maximum among all possible choices of subarrays. Examples: Input : arr[] = [2, 5, 1, 2, 7, 3, 0] K = 2 Output : 2 5 7 3 We can choose two arrays of maximum sum as [2, 5] and [7, 3], the sum of
12 min read
Count maximum non-overlapping subarrays with given sum
Given an array arr[] consisting of N integers and an integer target, the task is to find the maximum number of non-empty non-overlapping subarrays such that the sum of array elements in each subarray is equal to the target. Examples: Input: arr[] = {2, -1, 4, 3, 6, 4, 5, 1}, target = 6Output: 3Expla
7 min read
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