Skip to content

Commit 2b072ce

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

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* TC: O(n^2)
3+
* SC: O(1)
4+
* */
5+
function maxProfit(prices: number[]): number {
6+
const n = prices.length;
7+
8+
let max = 0;
9+
10+
for (let i = 0; i < n; i++) {
11+
let currentMax = 0;
12+
13+
for (let j = i + 1; j < n; j++) {
14+
if (prices[i] <= prices[j]) {
15+
const profit = prices[j] - prices[i];
16+
17+
currentMax = Math.max(currentMax, profit);
18+
}
19+
}
20+
21+
max = Math.max(max, currentMax);
22+
}
23+
24+
return max;
25+
}
26+
27+
const tc1 = maxProfit([7, 1, 5, 3, 6, 4]);
28+
console.info("🚀 : tolluset.ts:5: tc1=", tc1); // 5
29+
30+
const tc2 = maxProfit([7, 6, 4, 3, 1]);
31+
console.info("🚀 : tolluset.ts:8: tc2=", tc2); // 0

0 commit comments

Comments
 (0)