maximum-twin-sum-of-a-linked-list.dart (700B)
1 //Find the maximum value of all twins in a linked list. 2 //A twin is the n and linked-list.length - 1 - n values combined together. 3 //The time complexity of my code is O(n) because it simply iterates through the list 4 //once and then again a second time. 5 //Time: 424ms Beats: 100% 6 //Memory: 211.5MB Beats: 50% 7 8 class Solution { 9 int pairSum(ListNode? head) { 10 List<int> vals = []; 11 while(head != null){ 12 vals.add(head?.val ?? 0); 13 head = head?.next; 14 } 15 int max = 0; 16 for(int i = 0 ; i < vals.length / 2 ; ++i){ 17 if(max < vals[i] + vals[vals.length - 1 - i]){ 18 max = vals[i] + vals[vals.length - 1 - i]; 19 } 20 } 21 return max; 22 } 23 }