-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQ2130MaximumTwinSum.java
More file actions
43 lines (37 loc) · 1.1 KB
/
Q2130MaximumTwinSum.java
File metadata and controls
43 lines (37 loc) · 1.1 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
/*
@b-knd (jingru) on 01 August 2022 11:11:00
*/
class Solution {
//Solution using stack (two pass)
public int pairSum(ListNode head) {
Stack<Integer> stack = new Stack<>();
ListNode temp = head;
int max = 0;
//push value to stack
while(temp != null){
stack.push(temp.val);
temp = temp.next;
}
//traverse linked list once again adding value with first element in stack using pop(), find max of sum using Math.max
temp = head;
while(temp != null){
max = Math.max(max, temp.val+stack.pop());
temp = temp.next;
}
return max;
}
//Solution using arraylist
public int pairSum(ListNode head) {
List<Integer> list = new ArrayList<>();
while(head != null) {
list.add(head.val);
head = head.next;
}
int n = list.size();
int max = 0;
for(int i = 0; i < n/2; i++) {
max = Math.max(max, list.get(i) + list.get(n - 1 - i));
}
return max;
}
}