diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 3b3ec304..3adcf8d2 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -87,6 +87,7 @@ | 771 | [Jewels and Stones](https://leetcode.com/problems/jewels-and-stones/) | [C](./src/771.c) | Easy | | 852 | [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/) | [C](./src/852.c) | Easy | | 876 | [Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) | [C](./src/876.c) | Easy | +| 901 | [Online Stock Span](https://leetcode.com/problems/online-stock-span/) | [C](./src/901.c) | Medium | | 905 | [Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/) | [C](./src/905.c) | Easy | | 917 | [Reverse Only Letters](https://leetcode.com/problems/reverse-only-letters/) | [C](./src/917.c) | Easy | | 938 | [Range Sum of BST](https://leetcode.com/problems/range-sum-of-bst/) | [C](./src/938.c) | Easy | diff --git a/leetcode/src/901.c b/leetcode/src/901.c new file mode 100644 index 00000000..efa712b6 --- /dev/null +++ b/leetcode/src/901.c @@ -0,0 +1,68 @@ +// Use monotonic stack. +// Keep the stack of monotonically increasing price and index. + +// Runtime: O(n) +// Space: O(n) +typedef struct stack{ + int price; + int index; + struct stack* previous; +} Stack; + + +typedef struct { + int index; + Stack* stackPointer; + Stack* sentry; +} StockSpanner; + + +StockSpanner* stockSpannerCreate() { + Stack* sentry = (Stack *)malloc(sizeof(Stack)); + StockSpanner* result = (StockSpanner *)malloc(sizeof(StockSpanner)); + result->index = 0; + result->sentry = sentry; + result->stackPointer = sentry; + return result; +} + +int stockSpannerNext(StockSpanner* obj, int price) { + while(obj->stackPointer != obj->sentry && obj->stackPointer->price <= price){ + Stack* currStackPointer = obj->stackPointer; + obj->stackPointer = obj->stackPointer->previous; + free(currStackPointer); + } + + obj->index += 1; + int result = obj->index; + if (obj->stackPointer != obj->sentry){ + result -= obj->stackPointer->index; + } + + Stack* newStackItem = (Stack *)malloc(sizeof(Stack)); + newStackItem->index = obj->index; + newStackItem->price = price; + newStackItem->previous = obj->stackPointer; + obj->stackPointer = newStackItem; + + return result; +} + +void stockSpannerFree(StockSpanner* obj) { + while(obj->stackPointer != obj->sentry){ + Stack* currStackPointer = obj->stackPointer; + obj->stackPointer = obj->stackPointer->previous; + free(currStackPointer); + } + + free(obj->sentry); + free(obj); +} + +/** + * Your StockSpanner struct will be instantiated and called as such: + * StockSpanner* obj = stockSpannerCreate(); + * int param_1 = stockSpannerNext(obj, price); + + * stockSpannerFree(obj); + */