File tree 1 file changed +59
-0
lines changed
1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change
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
+ const llLength = ( head ) => {
16
+ let count = 0 ;
17
+ while ( head ) {
18
+ head = head . next ;
19
+ count ++ ;
20
+ }
21
+ return count ;
22
+ } ;
23
+
24
+ const reverseLL = ( head , len ) => {
25
+ let count = 0 ;
26
+ let temp = null ;
27
+ while ( count < len ) {
28
+ const next = head . next ;
29
+ head . next = temp ;
30
+ temp = head ;
31
+ head = next ;
32
+ count ++ ;
33
+ }
34
+ return temp ;
35
+ } ;
36
+
37
+ var pairSum = function ( head ) {
38
+ const mid = llLength ( head ) / 2 ;
39
+
40
+ // get the right starting pointer
41
+ let count = 0 ;
42
+ let rightPointer = head ;
43
+ while ( count < mid ) {
44
+ rightPointer = rightPointer . next ;
45
+ count ++ ;
46
+ }
47
+
48
+ // reverse the left portion of the array
49
+ leftPointer = reverseLL ( head , mid ) ;
50
+
51
+ let max = 0 ;
52
+ while ( leftPointer && rightPointer ) {
53
+ max = Math . max ( leftPointer . val + rightPointer . val , max ) ;
54
+ leftPointer = leftPointer . next ;
55
+ rightPointer = rightPointer . next ;
56
+ }
57
+
58
+ return max ;
59
+ } ;
You can’t perform that action at this time.
0 commit comments