703668. Maximum prefix sum for a given range

Easy

Maximum prefix sum for a given range

Summary

Given an array and a query range, find the maximum prefix sum that lies within the query range. This problem involves arrays and segment trees, which are advanced data structures.

Detailed Explanation

The problem can be solved by using a segment tree to efficiently compute prefix sums and then finding the maximum prefix sum within the given range. Here's a step-by-step breakdown of the solution:

  1. Initialize an empty segment tree.

  2. Create a function buildTree that builds the segment tree from the given array. This function recursively constructs the segment tree by calculating the cumulative sum for each segment and storing it in the tree.

    • Time complexity: O(n)
    • Space complexity: O(n)
  3. Create a function queryRange that finds the maximum prefix sum within the given query range. This function starts from the root of the segment tree, recursively exploring both left and right subtrees until it reaches a leaf node.

    • Time complexity: O(log n)
    • Space complexity: O(1)
  4. To find the maximum prefix sum, start by querying the segment tree with the query range as the input. This will give you the maximum prefix sum within that range.

  5. If the query range is [L, R], where L and R are indices in the array, then:

    • QueryRange(L, R) = maximum(prefixSum(L), prefixSum(R))
  6. The prefixSum function calculates the cumulative sum of elements from index 0 to a given index.

  7. Combine these two queries to find the maximum prefix sum within the query range.

Time Complexity Analysis

The time complexity for building the segment tree is O(n). Querying the segment tree has a time complexity of O(log n), as we recursively traverse the tree until we reach the leaf node. Therefore, the overall time complexity is O(n + log n).

Space Complexity Analysis

The space complexity for the segment tree is O(n). The query function uses constant space, so the overall space complexity remains O(n).

Here's an example of how this problem can be solved:

#include <iostream>
using namespace std;

class SegmentTree {
public:
    int buildTree(int arr[], int n) {
        // Initialize the segment tree
        int tree[4 * n];
        for (int i = 0; i < n; i++) {
            tree[i + n] = arr[i];
        }

        for (int i = n; i > 0; i /= 2) {
            for (int j = 0; j <= i; j++) {
                tree[j + 2 * i] = tree[2 * j + i] + tree[2 * j + i + 1];
            }
        }

        return n;
    }

    int queryRange(int arr[], int L, int R) {
        // Initialize the result as negative infinity
        int res = -1000000;

        for (int i = L; i <= R; i++) {
            res = max(res, prefixSum(arr, i));
        }

        return res;
    }

    int prefixSum(int arr[], int index) {
        if (index < 0 || index >= sizeof(arr) / sizeof(arr[0])) {
            // Handle out-of-bounds errors
            cout << "Error: Index is out of bounds." << endl;
            return -1;  // Return an error value
        }

        int sum = arr[index];
        while (index > 0 && index < sizeof(arr) / sizeof(arr[0])) {
            if (index % 2 == 1)
                index++;
            index /= 2;

            sum += arr[index];
        }
        return sum;
    }
};

int main() {
    int arr[] = {3, -1, 6, 4, -8, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    SegmentTree tree;
    int result = tree.queryRange(arr, 2, 5);
    cout << "Maximum prefix sum within the range [2, 5] is: " << result << endl;

    return 0;
}

Optimized Solutions

Java

View on GeeksforGeeks
public class Main {
    public static void main(String[] args) {
        int[] arr = {3, -1, 6, 4, -8, 12};
        int n = arr.length;
        SegmentTree tree = new SegmentTree();
        int result = tree.queryRange(arr, 2, 5);
        System.out.println("Maximum prefix sum within the range [2, 5] is: " + result);
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.