Repository navigation
Expand file tree
/
Copy pathproblem2103.java
More file actions
92 lines (69 loc) · 1.79 KB
/
Copy pathproblem2103.java
File metadata and controls
92 lines (69 loc) · 1.79 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
//2130. Maximum Twin Sum of a Linked List
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class problem2103 {
public static int pairSum(ListNode head) {
int max = -1;
int length=0;
int c=1;
ListNode p1= head;
while (p1!=null) {
length++;
p1=p1.next;
}
p1=head;
ListNode p2 = head;
while(c<=length/2 && p2!=null)
{
c++;
p2=p2.next;
}
p2 = reverseList(p2);
while(p1!=null && p2!=null)
{
max=Math.max(max, (p1.val+p2.val));
p1=p1.next;
p2=p2.next;
}
System.out.println("max :" + max);
return max;
}
public static ListNode reverseList(ListNode head) {
ListNode curr = head;
ListNode nex = head.next;
ListNode prev= null;
while(nex!=null)
{
curr.next= prev;
prev=curr;
curr=nex;
nex=curr.next;
}
curr.next=prev;
return curr;
}
public static void printList(ListNode head) {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.val + " -> ");
temp = temp.next;
}
System.out.println("null");
}
public static void main(String[] args) {
int[] arr = {1,100000};
ListNode head = new ListNode(arr[0]);
ListNode current = head;
for (int i = 1; i < arr.length; i++) {
current.next = new ListNode(arr[i]);
current = current.next;
}
System.out.println(pairSum(head));
}
}