forked from abhishektripathi66/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaximumTwinSumofaLinkedList.java
104 lines (93 loc) · 2.67 KB
/
MaximumTwinSumofaLinkedList.java
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
93
94
95
96
97
98
99
100
101
102
103
104
/**
2130. Maximum Twin Sum of a Linked List
Solved
Medium
Topics
Companies
Hint
In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4.
The twin sum is defined as the sum of a node and its twin.
Given the head of a linked list with even length, return the maximum twin sum of the linked list.
**/
/**
* 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; }
* }
*/
/** My Solution **/
class Solution {
public int pairSum(ListNode head) {
List<Integer> a = new ArrayList<>();
while(head!=null){
a.add(head.val);
head=head.next;
}
int i=0;
int sum=0;
int j=a.size()-1;
while(i<j){
sum=Math.max(sum,a.get(i)+a.get(j));
i++;j--;
}
return sum;
}
}
/** best solution **/
class Solution {
private static int [] a = new int[100000];
public int pairSum(ListNode head) {
// APPROACH 1 :
// ListNode fast =head;
// ListNode slow=head;
// while(fast.next!=null && fast.next.next!=null){
// fast=fast.next.next;
// slow=slow.next;
// }
// ListNode temp=reverse(slow.next);
// slow.next=temp;
// ListNode p1=head;
// ListNode p2=slow.next;
// System.out.print(p1.val+" "+p2.val);
// int maxSum=Integer.MIN_VALUE;
// while(p2!=null){
// maxSum=Math.max(maxSum,p1.val+p2.val);
// p1=p1.next;
// p2=p2.next;
// }
// return maxSum;
// }
// public static ListNode reverse(ListNode head){
// ListNode curr=head;
// ListNode prev=null;
// ListNode agla=null;
// while(curr!=null){
// agla=curr.next;
// curr.next=prev;
// prev=curr;
// curr=agla;
// }
// return prev;
// APPROACH 2 :
final int[] arr = a;
int size = 0;
while(head != null){
arr[size++] = head.val;
head = head.next;
}
int m =size/2;
int maxSum = 0;
for(int i=0;i<m;i++){
--size;
if(arr[i] + arr[size] > maxSum){
maxSum = arr[i] + arr[size];
}
}
return maxSum;
}
}