Skip to content

Commit d7ce786

Browse files
committed
Add solution #901
1 parent 520dc4d commit d7ce786

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,7 @@
248248
876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy|
249249
884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy|
250250
890|[Find and Replace Pattern](./0890-find-and-replace-pattern.js)|Medium|
251+
901|[Online Stock Span](./0901-online-stock-span.js)|Medium|
251252
905|[Sort Array By Parity](./0905-sort-array-by-parity.js)|Easy|
252253
914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|
253254
916|[Word Subsets](./0916-word-subsets.js)|Medium|

solutions/0901-online-stock-span.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* 901. Online Stock Span
3+
* https://leetcode.com/problems/online-stock-span/
4+
* Difficulty: Medium
5+
*
6+
* Design an algorithm that collects daily price quotes for some stock and returns the
7+
* span of that stock's price for the current day.
8+
*
9+
* The span of the stock's price in one day is the maximum number of consecutive days
10+
* (starting from that day and going backward) for which the stock price was less than
11+
* or equal to the price of that day.
12+
*
13+
* - For example, if the prices of the stock in the last four days is [7,2,1,2] and the
14+
* price of the stock today is 2, then the span of today is 4 because starting from
15+
* today, the price of the stock was less than or equal 2 for 4 consecutive days.
16+
*
17+
* - Also, if the prices of the stock in the last four days is [7,34,1,2] and the price
18+
* of the stock today is 8, then the span of today is 3 because starting from today,
19+
* the price of the stock was less than or equal 8 for 3 consecutive days.
20+
*
21+
* Implement the StockSpanner class:
22+
* - StockSpanner() Initializes the object of the class.
23+
* - int next(int price) Returns the span of the stock's price given that today's
24+
* price is price.
25+
*/
26+
27+
var StockSpanner = function() {
28+
this.stack = [];
29+
};
30+
31+
/**
32+
* @param {number} price
33+
* @return {number}
34+
*/
35+
StockSpanner.prototype.next = function(price) {
36+
let count = 1;
37+
38+
while (this.stack.length && price >= this.stack[this.stack.length - 1][0]) {
39+
count += this.stack[this.stack.length - 1][1];
40+
this.stack.pop();
41+
}
42+
43+
this.stack.push([price, count]);
44+
45+
return count;
46+
};

0 commit comments

Comments
 (0)