Skip to content

Commit c7fb410

Browse files
committed
solve: best time to by and sell stock 2
1 parent 2b072ce commit c7fb410

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

best-time-to-buy-and-sell-stock/tolluset.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,36 @@
11
/*
2+
* TC: O(n)
3+
* SC: O(1)
4+
* */
5+
function maxProfitV2(prices: number[]): number {
6+
const n = prices.length;
7+
8+
let min = Infinity,
9+
max = 0;
10+
11+
for (let i = 0; i < n; i++) {
12+
if (prices[i] < min) {
13+
min = prices[i];
14+
continue;
15+
}
16+
17+
if (prices[i] - min > max) {
18+
max = prices[i] - min;
19+
continue;
20+
}
21+
}
22+
23+
return max;
24+
}
25+
26+
const tc1V2 = maxProfitV2([7, 1, 5, 3, 6, 4]);
27+
console.info("🚀 : tolluset.ts:27: tc1V2=", tc1V2); // 5
28+
29+
const tc2V2 = maxProfitV2([7, 6, 4, 3, 1]);
30+
console.info("🚀 : tolluset.ts:30: tc2V2=", tc2V2); // 0
31+
32+
/*
33+
* @FAILED: Time Limit Exceeded
234
* TC: O(n^2)
335
* SC: O(1)
436
* */

0 commit comments

Comments
 (0)