![]() |
VOOZH | about |
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:
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:
In this Case, Maximum Prefix Sum = Maximum Prefix Sum of Left 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:
In this Case, Maximum Suffix Sum = Maximum Suffix Sum of Right 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:
In this Case, Maximum Sub-array Sum = Maximum Subarray Sum of Left Child
In this Case, Maximum Sub-array Sum = Maximum Subarray Sum of Right Child
In this Case, Maximum Subarray Sum = Maximum Prefix Sum of Right Child + Maximum Suffix Sum of Left Child
Implementation:
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.