I am looking at this stock span problem:
The stock span problem is a financial problem where we have a series of n daily price quotes for a stock and we need to calculate the span of stock’s price for all n days.
The span Si of the stock’s price on a given day i is defined as the maximum number of consecutive days just before the given day, for which the price of the stock on the current day is less than or equal to its price on the given day.
In this description an algorithm is explained:
Computing Spans with a Stack
The output for the example is supposed to be {1,1,2,1,2,3,6,1}, but my code outputs {1,1,2,2,2,3,6,7}
#include <stdio.h>
#include <stdlib.h>
#define SIZE 8
typedef int element;
typedef struct StackType {
element elem[SIZE];
int top;
} StackType;
void init(StackType *A) {
A->top = -1;
}
int isEmpty(StackType *A) {
return A->top == -1;
}
int isFull(StackType *A) {
return A->top == SIZE - 1;
}
void push(StackType *A, element i) {
if (isFull(A)) {
printf("FULL\n");
return;
}
A->top++;
A->elem[A->top] = i;
}
element pop(StackType *A) {
if (isEmpty(A)) {
printf("Empty\n");
return 0;
}
element temp = A->elem[A->top];
A->top--;
return temp;
}
void spans(StackType *A, int X[], int S[]) {
for (int i = 0; i < SIZE; i++) {
while (!isEmpty(A) && (X[A->top] <= X[i]))
pop(A);
if (isEmpty(A))
S[i] = i + 1;
else
S[i] = i - (A->top);
push(A, i);
}
while (!isEmpty(A))
pop(A);
return;
}
int main() {
StackType A;
init(&A);
int X[SIZE] = { 60, 30, 40, 10, 20, 30, 50, 40 };
int S[SIZE];
spans(&A, X, S);
for (int i = 0; i < SIZE; i++)
printf("[%d] ", S[i]);
printf("\n");
return 0;
}
I debugged the function void spans, and I saw A->top doesn't change in the right way. For example, when i = 2, A->top should be 2, but in reality, A->top is 1. There seems something wrong with function pop and push, but I couldn't find the problem.
