-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPairSum.java
More file actions
59 lines (43 loc) · 1.39 KB
/
Copy pathPairSum.java
File metadata and controls
59 lines (43 loc) · 1.39 KB
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
package LeetcodePractice;
import java.util.ArrayList;
import java.util.List;
public class PairSum {
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public int pairSum(ListNode head) {
List<Integer> values = new ArrayList<>();
ListNode current = head;
while (current != null) {
values.add(current.val);
current = current.next;
}
int maxSum = 0;
int n = values.size();
for (int i = 0; i < n / 2; i++) {
int twinSum = values.get(i) + values.get(n - 1 - i);
maxSum = Math.max(maxSum, twinSum);
}
return maxSum;
}
public static ListNode createList(int[] arr) {
ListNode dummy = new ListNode(0);
ListNode current = dummy;
for (int val : arr) {
current.next = new ListNode(val);
current = current.next;
}
return dummy.next;
}
public static void main(String[] args) {
int[] input = {5, 4, 2, 1};
ListNode head = createList(input);
PairSum ps = new PairSum();
int result = ps.pairSum(head);
System.out.println("Maximum Twin Sum: " + result);
}
}