Skip to content

Commit d94a113

Browse files
authored
Merge pull request #2693 from aadil42/patch-69
2 parents 4716012 + ff3a05d commit d94a113

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Diff for: javascript/2130-maximum-twin-sum-of-a-linked-list.js

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val, next) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.next = (next===undefined ? null : next)
6+
* }
7+
*/
8+
9+
/**
10+
* Linear Time
11+
* Time O(n) | Space O(1)
12+
* @param {ListNode} head
13+
* @return {number}
14+
*/
15+
var pairSum = function (head) {
16+
const mid = llLength(head) / 2;
17+
const rightPointer = getRightPointer(head, mid);
18+
const leftPointer = reverseLL(head, mid);
19+
20+
return getMax(leftPointer, rightPointer);
21+
};
22+
23+
var getMax = (leftPointer, rightPointer) => {
24+
let max = 0;
25+
while (leftPointer && rightPointer) {
26+
max = Math.max(leftPointer.val + rightPointer.val, max);
27+
leftPointer = leftPointer.next;
28+
rightPointer = rightPointer.next;
29+
}
30+
return max;
31+
}
32+
var getRightPointer = (head, mid) => {
33+
let count = 0;
34+
let rightPointer = head;
35+
while (count < mid) {
36+
rightPointer = rightPointer.next;
37+
count++;
38+
}
39+
return rightPointer;
40+
}
41+
42+
var llLength = (head) => {
43+
let count = 0;
44+
while (head) {
45+
head = head.next;
46+
count++;
47+
}
48+
return count;
49+
};
50+
51+
var reverseLL = (head, len) => {
52+
let count = 0;
53+
let temp = null;
54+
while (count < len) {
55+
const next = head.next;
56+
head.next = temp;
57+
temp = head;
58+
head = next;
59+
count++;
60+
}
61+
return temp;
62+
};

0 commit comments

Comments
 (0)