赞
踩
Design an algorithm that collects daily price quotes for some stock and returns the span of that stock’s price for the current day.
The span of the stock’s price in one day is the maximum number of consecutive days (starting from that day and going backward) for which the stock price was less than or equal to the price of that day.
Implement the StockSpanner class:
Input:
[“StockSpanner”, “next”, “next”, “next”, “next”, “next”, “next”, “next”]
[[], [100], [80], [60], [70], [60], [75], [85]]
Output:
[null, 1, 1, 1, 2, 1, 4, 6]
Explanation
StockSpanner stockSpanner = new StockSpanner();
stockSpanner.next(100); // return 1
stockSpanner.next(80); // return 1
stockSpanner.next(60); // return 1
stockSpanner.next(70); // return 2
stockSpanner.next(60); // return 1
stockSpanner.next(75); // return 4, because the last 4 prices (including today’s price of 75) were less than or equal to today’s price.
stockSpanner.next(85); // return 6
From: LeetCode
Link: 901. Online Stock Span
This code defines a StockSpanner struct with three fields: prices and spans are dynamically allocated arrays to store the price and span of each stock, and top is used to keep track of the stack’s top element index. The stockSpannerCreate function initializes a StockSpanner object, stockSpannerNext processes the next stock price and calculates its span, and stockSpannerFree cleans up the allocated memory to prevent memory leaks.
typedef struct { int* prices; int* spans; int top; } StockSpanner; StockSpanner* stockSpannerCreate() { StockSpanner* spanner = (StockSpanner*)malloc(sizeof(StockSpanner)); spanner->prices = (int*)malloc(sizeof(int) * 10000); // Assuming at most 10^4 calls. spanner->spans = (int*)malloc(sizeof(int) * 10000); // Same assumption as above. spanner->top = -1; // Initialize stack top as -1 indicating empty stack. return spanner; } int stockSpannerNext(StockSpanner* obj, int price) { int span = 1; while (obj->top >= 0 && obj->prices[obj->top] <= price) { span += obj->spans[obj->top]; // Add the span of elements that are less than or equal to the current price. obj->top--; // Pop the elements that are less than or equal to the current price. } obj->top++; obj->prices[obj->top] = price; // Push the current price onto the stack. obj->spans[obj->top] = span; // Push the current span onto the stack. return span; } void stockSpannerFree(StockSpanner* obj) { free(obj->prices); // Free the allocated memory for prices. free(obj->spans); // Free the allocated memory for spans. free(obj); // Finally, free the object itself. } /** * Your StockSpanner struct will be instantiated and called as such: * StockSpanner* obj = stockSpannerCreate(); * int param_1 = stockSpannerNext(obj, price); * stockSpannerFree(obj); */
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。