forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
2130-maximum-twin-sum-of-a-linked-list.js
62 lines (57 loc) · 1.26 KB
/
2130-maximum-twin-sum-of-a-linked-list.js
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
53
54
55
56
57
58
59
60
61
62
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* Linear Time
* Time O(n) | Space O(1)
* @param {ListNode} head
* @return {number}
*/
var pairSum = function (head) {
const mid = llLength(head) / 2;
const rightPointer = getRightPointer(head, mid);
const leftPointer = reverseLL(head, mid);
return getMax(leftPointer, rightPointer);
};
var getMax = (leftPointer, rightPointer) => {
let max = 0;
while (leftPointer && rightPointer) {
max = Math.max(leftPointer.val + rightPointer.val, max);
leftPointer = leftPointer.next;
rightPointer = rightPointer.next;
}
return max;
}
var getRightPointer = (head, mid) => {
let count = 0;
let rightPointer = head;
while (count < mid) {
rightPointer = rightPointer.next;
count++;
}
return rightPointer;
}
var llLength = (head) => {
let count = 0;
while (head) {
head = head.next;
count++;
}
return count;
};
var reverseLL = (head, len) => {
let count = 0;
let temp = null;
while (count < len) {
const next = head.next;
head.next = temp;
temp = head;
head = next;
count++;
}
return temp;
};