You are designing a real-time data processing system that analyzes a stream of incoming data packets. Each packet has a numerical "pulse strength." The system uses a stack to maintain a record of significant pulse strengths. When a new, stronger pulse arrives, it can render previous, weaker pulses insignificant.
The system processes a sequence of N pulse strengths according to these rules:
- For each incoming pulse A[i], compare it to the pulse at the top of the stack.
- As long as the stack is not empty and the pulse at the top is weaker than or equal to the incoming pulse A[i], remove it from the stack.
- The number of pulses removed in this step is the "pulse skip count" for the incoming pulse A[i].
- After removing all weaker/equal pulses, push the incoming pulse A[i] onto the stack.
Your task is to calculate the total "disruption" in the stream, which is the sum of the pulse skip counts for all N packets.
The first line of input contains a single integer N, representing the number of data packets.
The second line contains N space-separated integers, A, representing the pulse strengths.
The output should be a single integer representing the total sum of all pulse skip counts.
If the stack is empty or the incoming pulse is strictly weaker than the pulse at the top of the stack, no elements are removed, and the skip count for that pulse is 0.
6
3 1 4 2 5 1
4
Let's trace the stack and the total skip count.
- Pulse 3: Stack is empty. Push 3. Skip Count: 0. Stack: [3]. Total: 0.
- Pulse 1: 1 is not greater than the top (3). Push 1. Skip Count: 0. Stack: [3, 1]. Total: 0.
- Pulse 4: 4 is greater than top (1). Pop 1. 4 is greater than new top (3). Pop 3. Stack is now empty. Skip Count: 2. Push 4. Stack: [4]. Total: 2.
- Pulse 2: 2 is not greater than top (4). Push 2. Skip Count: 0. Stack: [4, 2]. Total: 2.
- Pulse 5: 5 is greater than top (2). Pop 2. 5 is greater than new top (4). Pop 4. Stack is now empty. Skip Count: 2. Push 5. Stack: [5]. Total: 2 + 2 = 4.
- Pulse 1: 1 is not greater than top (5). Push 1. Skip Count: 0. Stack: [5, 1]. Total: 4.
The final sum of skip counts is 4.
5
1 2 3 4 5
2
- Pulse 1: Push 1. Skip: 0. Stack: [1]. Total: 0.
- Pulse 2: Pop 1. Skip: 1. Push 2. Stack: [2]. Total: 1.
- Pulse 3: Pop 2. Skip: 1. Push 3. Stack: [3]. Total: 2.
- Pulse 4: Pop 3. Skip: 1. Push 4. Stack: [4]. Total: 3.
- Pulse 5: Pop 4. Skip: 1. Push 5. Stack: [5]. Total: 4.
The final sum is 4.
The expected time complexity is O(N), because each element is pushed onto and popped from the stack at most once.
1 <= N <= 10^5
1 <= A[i] <= 10^9
Time limit: 1 sec