-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
35 lines (31 loc) · 781 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
import { ListNode } from "../mod.ts";
export default function pairSum(head: ListNode | null): number {
if (!head) return 0;
let left = head;
let right = head;
const node_to_prev = new WeakMap<ListNode, null | ListNode>();
let sum = 0;
while (right) {
if (right.next) {
node_to_prev.set(right.next, right);
right = right.next;
} else {
break;
}
}
while (left !== right) {
sum = Math.max(sum, left.val + right.val);
if (left.next) {
left = left.next;
} else {
break;
}
const prev = node_to_prev.get(right);
if (prev) {
right = prev;
} else {
break;
}
}
return sum;
}