I’m using java to solve this question: https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ :
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.
I’m using an ArrayList to store the members of linked list and then calculating sum, still a beginner to dsa, but I’m still learning. Why am i getting memory limit exceeded as my output?? Here’s my answer:
class Solution {
public int pairSum(ListNode head) {
ArrayList<Integer> temp = new ArrayList<>();
ListNode current = head;
while(current != null){
temp.add(current.val);
}
int n = temp.size();
int sum = 0;
int maxSum = 0;
if(temp.size() == 2){
return temp.get(0) + temp.get(1);
}
for(int i = 0; i < n/2; i++){
sum = sum + temp.get(i) + temp.get(n - i - 1);
maxSum = Math.max(sum, maxSum);
}
return maxSum;
}
}
I have tried to find the answer on gemini but all in vain. Is it because some linked lists can be huge in size and arraylist is consuming memory for such inputs? somebody help me out please.