【发布时间】:2021-11-30 03:42:49
【问题描述】:
股票跨度问题是一个财务问题,我们有一系列n个股票的每日报价,我们需要计算所有n的股票价格跨度> 天。
给定日期股票价格的跨度Sii定义为在给定日期之前的最大连续天数当天,股票当天的价格小于或等于给定日期的价格。
在this description 中解释了一个算法:
使用堆栈计算 Span
示例的输出应该是 {1,1,2,1,2,3,6,1},但我的代码输出 {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;
}
我调试了函数void spans,我看到A->top 没有以正确的方式改变。比如i = 2时,A->top应该是2,但实际上A->top是1。 pop 和 push 函数似乎有问题,但我找不到问题。
【问题讨论】:
-
如果我们不知道这段代码在功能上应该做什么,我们将无法帮助您。请告诉我们此代码的功能或规格。
-
您确定堆栈结构及其功能正常工作吗?在使用 span 函数之前,您是否尝试过仅测试和调试这些部分?
-
@RBarryYoung 好吧,我们总是在发帖说用谷歌搜索东西是多么容易,如果你搜索“股票跨度”,前两个点击是 - 惊喜,惊喜 - geeksforgeeks 和leetcode.
-
@SteveSummit 问题描述应该包含在问题中。即使 OP 包含指向 LeetCode 等的链接,描述也不应该依赖于外部网站。如果“库存跨度”是 CS 中的标准问题/描述,并且足以描述 OPs 代码的功能代码,那么我会撤回我的担忧,但我以前从未听说过,LeetCode 和 GeeksForGeeks 都不是权威指南这样的。 (首先,他们经常错误地命名标准的众所周知的问题,例如 Change-Making Problem)。
-
@RBarryYoung,问题解决了。
标签: c algorithm pointers stack stock