![]() |
VOOZH | about |
Given an array arr[] of integers and a list of queries. Each query consists of two indices, leftIndex and rightIndex, defining a range in the array. For each query, calculate the maximum prefix sum within the given range.
Note: A prefix sum is the sum of all elements from the start of the range up to a certain point within the range.
Examples:
Input: arr[] = [ -1, 2, 3, -5 ]
leftIndex[] = [ 0, 1 ], rightIndex = [ 3, 3 ]
Output: 4 5
Explanation: For the range [0, 3], the prefix sums are [-1, 1, 4, -1]. The maximum is 4. For the range [1, 3], the prefix sums are [2, 5, 0]. The maximum is 5.Input: arr = [1, -2, 3, 4, -5], leftIndex = [0, 2, 1], rightIndex = [4, 3, 3]
Output: 6 7 5
Explanation: For the range [0, 4], the prefix sums are [1, -1, 2, 6, 1]. The maximum is 6. For the range [2, 3], the prefix sums are [3, 7]. The maximum is 7. For the range [1, 3], the prefix sums are [-2, 1, 5]. The maximum is 5.
Table of Content
The idea is to run a loop from l to r and calculate max prefix sum from l to r for every query.
6 7 5
The idea is to use a segment tree to efficiently answer range queries for the maximum prefix sum. Each node in the segment tree stores both the total sum of its segment and the maximum prefix sum within that segment, so that when two segments are merged, the overall prefix sum can be computed as the maximum of the left segment’s prefix sum and the sum of the left segment plus the right segment’s prefix sum.
Segment Tree Structure:
The segment tree is structured as an array-based binary tree. The leaf nodes represent individual elements of the input array. Each internal node represents a merged segment where its stored sum is the total sum of the leaves in its segment and its prefix sum is computed as the maximum between the left child’s prefix sum and the left child’s sum plus the right child’s prefix sum. For a node at index i, its left child is at 2i+1, its right child at 2i+2, and its parent is at (i-1)/2.
Follow the below given steps:
6 7 5