Skip to content

Commit cf381d1

Browse files
committed
260th Commit
1 parent 5de5051 commit cf381d1

File tree

4 files changed

+55
-1
lines changed

4 files changed

+55
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -295,9 +295,10 @@ Problems:
295295
| Monotonic Stack | | | |
296296
| ----------------------- | --------------- | ------ | ---- |
297297
| 739. Daily Temperatures | [Solution][739] | Medium | 詳解 |
298-
| 901. Online Stock Span | Solution | Medium | 詳解 |
298+
| 901. Online Stock Span | [Solution][901] | Medium | 詳解 |
299299

300300
[739]: ./src/page-7/739.%20Daily%20Temperatures/dailyTemperatures.ts
301+
[901]: ./src/page-9/901.%20Online%20Stock%20Span/StockSpanner.ts
301302

302303
## Advanced - Top Interview 150
303304

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# 72. 股票價格跨距 (Online Stock Span)
2+
3+
設計一個演算法,收集某些股票的每日報價並返回該股票當日價格的**跨距**
4+
5+
當日股票價格的**跨距**是指股票價格小於或等於當日價格的最大連續天數(從該日開始往回算)。
6+
7+
- 例如,如果最近四天股票的價格是 `[7,2,1,2]`,今天股票的價格是 `2`,那麼今天的跨距是 `4`,因為從今天開始,股票的價格連續 `4` 天小於或等於 `2`
8+
- 另外,如果最近四天股票的價格是 `[7,34,1,2]`,今天股票的價格是 `8`,那麼今天的跨距是 `3`,因為從今天開始,股票的價格連續 `3` 天小於或等於 `8`
9+
10+
實作 `StockSpanner` 類別:
11+
12+
- `StockSpanner()` 初始化類別的物件。
13+
- `next(price: number): number` 給出今天的股價 `price`,返回該股票價格的**跨距**
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { StockSpanner } from './StockSpanner';
2+
3+
describe('901. Online Stock Span', () => {
4+
test('StockSpanner', () => {
5+
const stockSpanner = new StockSpanner();
6+
expect(stockSpanner.next(100)).toBe(1);
7+
expect(stockSpanner.next(80)).toBe(1);
8+
expect(stockSpanner.next(60)).toBe(1);
9+
expect(stockSpanner.next(70)).toBe(2);
10+
expect(stockSpanner.next(60)).toBe(1);
11+
expect(stockSpanner.next(75)).toBe(4);
12+
expect(stockSpanner.next(85)).toBe(6);
13+
});
14+
});
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* Accepted
3+
*/
4+
export class StockSpanner {
5+
private stack: [number, number][];
6+
7+
constructor() {
8+
// Initialize the stack, where each element is [price, span]
9+
this.stack = [];
10+
}
11+
12+
next(price: number): number {
13+
let span = 1;
14+
15+
// While stack is not empty and the current price is greater than or equal to the price on top of the stack
16+
while (this.stack.length > 0 && this.stack[this.stack.length - 1][0] <= price) {
17+
// Pop the top of the stack and add its span to the current span
18+
span += (this.stack.pop() as [number, number])[1];
19+
}
20+
21+
// Push the current price and its span onto the stack
22+
this.stack.push([price, span]);
23+
24+
return span;
25+
}
26+
}

0 commit comments

Comments
 (0)