-
Notifications
You must be signed in to change notification settings - Fork 70
/
res.ts
43 lines (36 loc) · 1.23 KB
/
res.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
function maxProfit(prices: number[]): number {
const minList = new Array(prices.length).fill(Number.MAX_SAFE_INTEGER);
const maxList = new Array(prices.length).fill(Number.MIN_SAFE_INTEGER);
let currentMin = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < prices.length; i++) {
if (currentMin > prices[i]) {
currentMin = prices[i];
}
minList[i] = currentMin;
}
let currentMax = Number.MIN_SAFE_INTEGER;
for (let i = prices.length - 1; i >= 0; i--) {
if (currentMax < prices[i]) {
currentMax = prices[i];
}
maxList[i] = currentMax;
}
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
maxProfit = Math.max(maxProfit, maxList[i] - minList[i]);
}
return maxProfit;
};
function maxProfit2(prices: number[]): number {
const minList = new Array(prices.length).fill(Number.MAX_SAFE_INTEGER);
let maxProfit = 0;
let currentMin = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < prices.length; i++) {
if (currentMin > prices[i]) {
currentMin = prices[i];
}
minList[i] = currentMin;
maxProfit = Math.max(maxProfit, prices[i] - minList[i]);
}
return maxProfit;
};