# Maximum prefix-sum for a given range in C++

## Problem statement

Given an array of n integers and q queries, each query having a range from l to r. Find the maximum prefix-sum for the range l – r.

## Example

If input array is arr[] = {-1, 2, 3, -5} and
queries = 2 and ranges are:
l = 0, r = 3
l = 1, r = 3 then output will be 4 and 5.
• The range (0, 3) in the 1st query has [-1, 2, 3, -5], since it is prefix, we have to start from -1. Hence, the max prefix sum will be -1 + 2 + 3 = 4
• The range (1, 3) in the 2nd query has [2, 3, -5], since it is prefix, we have to start from 2. Hence, the max prefix sum will be 2 + 3 = 5

## Algorithm

• build a segment tree where each node stores two values s(sum and prefix_sum), and do a range query on it to find the max prefix sums.
• For finding out the maximum prefix sum, we will require two things, one being the sum and the other prefix sum
• The merging will return two things, sum of the ranges and the prefix sum that will store the max(prefix.left, prefix.sum + prefix.right) in the segment trees
• The max prefix sum for any two range combining will either be the prefix sum from left side or the sum of left side+prefix sum of right side, whichever is max is taken into account.

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef struct node {
int sum;
int prefix;
} node;
node tree[4 * 10000];
void build(int *arr, int idx, int start, int end) {
if (start == end) {
tree[idx].sum = arr[start];
tree[idx].prefix = arr[start];
} else {
int mid = (start + end) / 2;
build(arr, 2 * idx + 1, start, mid);
build(arr, 2 * idx + 2, mid + 1, end);
tree[idx].sum = tree[2 * idx + 1].sum + tree[2 *
idx + 2].sum;
tree[idx].prefix = max(tree[2 * idx + 1].prefix,
tree[2 * idx + 1].sum + tree[2 * idx + 2].prefix);
}
}
node query(int idx, int start, int end, int l, int r) {
node result;
result.sum = result.prefix = -1;
if (start > r || end < l) {
return result;
}
if (start >= l && end <= r) {
return tree[idx];
}
int mid = (start + end) / 2;
if (l > mid) {
return query(2 * idx + 2, mid + 1, end, l, r);
}
if (r <= mid) {
return query(2 * idx + 1, start, mid, l, r);
}
node left = query(2 * idx + 1, start, mid, l, r);
node right = query(2 * idx + 2, mid + 1, end, l, r);
result.sum = left.sum + right.sum;
result.prefix = max(left.prefix, left.sum + right.prefix);
return result;
}
int main() {
int arr[] = { -2, -3, 4, -1, -2, 1, 5, -3 };
int n = sizeof(arr) / sizeof(arr);
build(arr, 0, 0, n - 1);
cout << "Result = " << query(0, 0, n - 1, 3, 5).prefix
<< endl;
return 0;
}

## Output

When you compile and execute above program. It generates following output −

Result = -1