- Given list of numbers, order is important, a span consists of
the number of concecutive numbers to the left of a given number that
are less than or equal to that number.
- Examples:
7 4 3 5 8
The span for 8 is 5
The span for 5 is 3
The span for 3 is 1
The span for 4 is 1
The span for 7 is 1
- Given a list of numbers, compute the span:
- A naive algorithm
Input array A of size n
Output s an array of spans
for(i=0;i<n;i++) {
k = 0
done = false
repeat
if (A[i-k] <= A[i]) {
k = k + 1
} else {
done = true
while (k < i)
s[i] = k
}
- For each element, step back through the array and compute the span
- What is the worst and best?
- A better algorithm
Make an empty queue D
for(i=0;i<n-1;i++) {
done = false
while (!D.isEmpty()) && (!done) {
if A[i] >= P[D.top()]
D.pop()
else
done = true
}
if D.isEmpty() then
h = -1
else
h = D.top()
S[i] = i-h
D.push(i)
}
- We then remove all spans that began with elements smaller than the
current element from the stack
- We put the index of the element that began the last
span onto the stack. (The current element)
- Consider:
8 6 2 4 2 5 7
Action Elements Stack
push 8 8 0
push 6 8 6 0 1
push 2 8 6 2 0 1 2
pop 2
push 4 8 6 4 0 1 3
push 2 8 6 4 2 0 1 3 4
pop 2
pop 4
push 5 8 6 5 0 1 5
pop 5
pop 6
push 7 8 7 0 6
- Argue that this is O(n)