-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.ts
52 lines (39 loc) · 995 Bytes
/
index.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
44
45
46
47
48
49
50
51
52
function part1(input: number[], target: number): number | undefined {
const set = new Set<number>();
for (let i = 0; i < input.length; i += 1) {
const current = input[i];
const diff = target - current;
if (set.has(diff)) {
return diff * current;
}
set.add(current);
}
return undefined;
}
function subtract(a: number, b: number): number {
return a - b;
}
function part2(input: number[], target: number): number | undefined {
const { length } = input;
const sorted = [...input].sort(subtract);
for (let i = 0; i < length - 2; i += 1) {
let l = i + 1;
let h = length - 1;
while (l < h) {
const current = sorted[i];
const low = sorted[l];
const high = sorted[h];
const sum = current + low + high;
if (sum === target) {
return current * low * high;
}
if (sum > target) {
h -= 1;
} else {
l += 1;
}
}
}
return undefined;
}
export { part1, part2 };