Home [Medium] Maximum Twin Sum of a Linked List
Post
Cancel

[Medium] Maximum Twin Sum of a Linked List

‘Maximum Twin Sum of a Linked List (Medium)`


📌 Problem

https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/

📌 Answer

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
/**
 * 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) {
        
        // check size
        ListNode checkSize = head;
        int size = 1;
        while (checkSize.next != null) {
            checkSize = checkSize.next;
            size++;
        }

        // put the value of 0 ~ size/2 to stack
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < size / 2; i++) {
            stack.push(head.val);
            head = head.next;
        }
        
        // make sum pop plus head.val / head = head.next;
        // compare prev sum with curr sum
        // - if curr sum is bigger, sum will be changed
        int sum = 0;
        while (head != null) {
            int curr = stack.pop() + head.val;
            if (sum < curr) sum = curr;
            head = head.next;
        }
        
        return sum; 
    }
}
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
class Solution {
    public int pairSum(ListNode head) {
        if (head == null) {
            return 0;
        }
        if (head.next == null) {
            return head.val;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        slow = reverse(slow);
        fast = head;
        int sum = Integer.MIN_VALUE;
        while (slow != null) {
            sum = Math.max(slow.val + fast.val, sum);
            slow = slow.next;
            fast = fast.next;
        }
        return sum;
    }
    
    public ListNode reverse(ListNode node) {
        if (node == null) {
            return null;
        }
        ListNode current = node;
        ListNode previous = null;
        while (current != null) {
            ListNode next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        return previous;
    }
}
This post is licensed under CC BY 4.0 by the author.

[Medium] Delete Node in a Linked List

[Medium] Merge In Between Linked Lists

Comments powered by Disqus.