Skip to content

Commit

Permalink
260th Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Shyam-Chen committed Dec 31, 2024
1 parent 5de5051 commit cf381d1
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -295,9 +295,10 @@ Problems:
| Monotonic Stack | | | |
| ----------------------- | --------------- | ------ | ---- |
| 739. Daily Temperatures | [Solution][739] | Medium | 詳解 |
| 901. Online Stock Span | Solution | Medium | 詳解 |
| 901. Online Stock Span | [Solution][901] | Medium | 詳解 |

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

## Advanced - Top Interview 150

Expand Down
13 changes: 13 additions & 0 deletions src/page-9/901. Online Stock Span/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# 72. 股票價格跨距 (Online Stock Span)

設計一個演算法,收集某些股票的每日報價並返回該股票當日價格的**跨距**

當日股票價格的**跨距**是指股票價格小於或等於當日價格的最大連續天數(從該日開始往回算)。

- 例如,如果最近四天股票的價格是 `[7,2,1,2]`,今天股票的價格是 `2`,那麼今天的跨距是 `4`,因為從今天開始,股票的價格連續 `4` 天小於或等於 `2`
- 另外,如果最近四天股票的價格是 `[7,34,1,2]`,今天股票的價格是 `8`,那麼今天的跨距是 `3`,因為從今天開始,股票的價格連續 `3` 天小於或等於 `8`

實作 `StockSpanner` 類別:

- `StockSpanner()` 初始化類別的物件。
- `next(price: number): number` 給出今天的股價 `price`,返回該股票價格的**跨距**
14 changes: 14 additions & 0 deletions src/page-9/901. Online Stock Span/StockSpanner.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { StockSpanner } from './StockSpanner';

describe('901. Online Stock Span', () => {
test('StockSpanner', () => {
const stockSpanner = new StockSpanner();
expect(stockSpanner.next(100)).toBe(1);
expect(stockSpanner.next(80)).toBe(1);
expect(stockSpanner.next(60)).toBe(1);
expect(stockSpanner.next(70)).toBe(2);
expect(stockSpanner.next(60)).toBe(1);
expect(stockSpanner.next(75)).toBe(4);
expect(stockSpanner.next(85)).toBe(6);
});
});
26 changes: 26 additions & 0 deletions src/page-9/901. Online Stock Span/StockSpanner.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Accepted
*/
export class StockSpanner {
private stack: [number, number][];

constructor() {
// Initialize the stack, where each element is [price, span]
this.stack = [];
}

next(price: number): number {
let span = 1;

// While stack is not empty and the current price is greater than or equal to the price on top of the stack
while (this.stack.length > 0 && this.stack[this.stack.length - 1][0] <= price) {
// Pop the top of the stack and add its span to the current span
span += (this.stack.pop() as [number, number])[1];
}

// Push the current price and its span onto the stack
this.stack.push([price, span]);

return span;
}
}

0 comments on commit cf381d1

Please sign in to comment.