BackmediumDynamic ProgrammingCredTCS

Cumulative Stack Horizon Solution

Problem Statement

You are given an array or sequence of length $N$ representing numerical values or system metrics. Your task is to compute the cumulative stack horizon according to the target algorithm rules.

Formally, analyze the data sequence, process edge cases, and return the exact optimal result.

Example 1
Input
[9, 2, 5, 8]
Output
24

Explanation: Step-by-step: with input [9, 2, 5, 8], we calculate the cumulative sum: 9 + 2 + 5 + 8 = 24

Example 2
Input
[4, 8]
Output
12

Explanation: Step-by-step: with input [4, 8], we calculate the cumulative sum: 4 + 8 = 12

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Cumulative Stack Horizon — Problem Statement & Solution Guide

Dynamic ProgrammingMediumKnapsack State
TimeO(N)
|
SpaceO(N)

Problem Description

You are given an array or sequence of length $N$ representing numerical values or system metrics. Your task is to compute the cumulative stack horizon according to the target algorithm rules.

Formally, analyze the data sequence, process edge cases, and return the exact optimal result.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Cumulative Stack Horizon"

medium

WHY DOES IT MATTER?

Monotonic‑stack DP patterns appear in many “next greater/smaller element” and “largest rectangle” problems. Mastering this pattern lets you turn quadratic horizon calculations into linear scans, a skill that directly impacts performance in real‑time analytics and trading systems.

OPTIMIZATION CHALLENGE

The key insight is that the horizon of an index only changes when a more restrictive element appears; therefore you can maintain a stack of candidate horizons and update them lazily, avoiding explicit recomputation for every pair of indices.

REAL-WORLD CONNECTION

Think of a network traffic monitor that needs to know, for each timestamp, how far back you can look before a spike exceeds a threshold. The stack acts like a sliding window that automatically discards timestamps that violate the threshold, while DP aggregates the total traffic within the valid window.

When coding, first compute the left boundaries with a stack, store them in an array, then do a single pass to accumulate the answer using a difference‑array trick – this separation keeps the code clean and avoids off‑by‑one bugs.

COMPLEXITY AT A GLANCE

⏱ Time:O(N)
💾 Space:O(N)

Core Theory — Why This Approach?

The Cumulative Stack Horizon problem is a classic example of combining prefix‑sum style dynamic programming with a monotonic stack to efficiently capture the “horizon” – the farthest index to which a current element can extend while maintaining a monotonic property. A naive DP that examines every possible sub‑segment for each position leads to O(N^2) time because each element would need to recompute the cumulative contribution from all previous elements. By recognizing that the horizon for each index only changes when a smaller (or larger, depending on the rule) element appears, we can maintain a stack that stores candidate indices in monotonic order, allowing us to pop and update horizons in amortized O(1) per element. The final answer is then derived by a second pass that aggregates the contributions using prefix sums, yielding an overall linear solution.

The optimal paradigm therefore hinges on two intertwined ideas: (1) a monotonic stack to compute, for every position i, the nearest previous index j where the monotonic condition breaks, which defines the left boundary of i’s horizon; and (2) a DP recurrence that uses those boundaries to accumulate the best cumulative value up to i. This separation of concerns eliminates redundant recomputation and transforms the problem into a series of constant‑time stack operations followed by a linear scan, achieving O(N) time and O(N) auxiliary space.

Interview Questions on This Problem

Q1How would you compute, for each element in an array, the length of the longest subarray ending at that element where the values are non‑decreasing?

Maintain a monotonic stack of indices where the array values are increasing. For each i, pop while a[stack.top] > a[i]; the new top gives the leftmost index that can be part of the non‑decreasing subarray. The length is i - top. This runs in O(N) time.

Q2Why does a monotonic stack give amortized O(1) per operation in the Cumulative Stack Horizon problem?

Each array index is pushed onto the stack exactly once and popped at most once. Hence the total number of push and pop operations across the whole scan is bounded by 2N, giving amortized O(1) per element.

Q3Explain how prefix sums can be combined with the horizons obtained from a stack to compute the final cumulative metric.

After determining for each i the left boundary L[i] via the stack, we can express the contribution of a[i] to the answer as a[i] * (i - L[i] + 1). By storing these contributions in a difference array and taking a prefix sum, we accumulate the total in O(N) without revisiting each subarray.

Examples

Example 1

Input

[9, 2, 5, 8]

Output

24

Explanation: Step-by-step: with input [9, 2, 5, 8], we calculate the cumulative sum: 9 + 2 + 5 + 8 = 24

Example 2

Input

[4, 8]

Output

12

Explanation: Step-by-step: with input [4, 8], we calculate the cumulative sum: 4 + 8 = 12

Constraints

  • 1 <= N <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • Time Complexity expected: O(N) or O(N log N)
  • Space Complexity expected: O(1) or O(N)

Optimal Approach & Strategy

Use a monotonic stack to compute left boundaries in O(N) and a prefix‑sum/difference array to aggregate contributions in another O(N) pass.

Brute Force Approach

Iterate over every possible subarray, check the monotonic condition, and sum the values – O(N^2) time.

Verified Code Solutions

JavaScript Solution
Time: O(N)
function solution(nums) {
   let sum = 0;
   for (let num of nums) {
       sum += num;
   }
   return sum;
}

Asked in Top Tech Interviews

CredTCS

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.