Skip to main content

Leetcode 2130

· One min read
Junhe Chen

This involves going to middle, reverse second half and then pair them up two pass apporach with extra memory would be using stack

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public int pairSum(ListNode head) {
ListNode slow = head;
ListNode fast = head;
// Get middle of the linked list.
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
// Reverse second half of the linked list.
ListNode nextNode, prev = null;
while (slow != null) {
nextNode = slow.next;
slow.next = prev;
prev = slow;
slow = nextNode;
}
ListNode start = head;
int maximumSum = 0;
while (prev != null) {
maximumSum = Math.max(maximumSum, start.val + prev.val);
prev = prev.next;
start = start.next;
}

return maximumSum;
}
}