Similar Problems
Similar Problems not available
Maximum Twin Sum Of A Linked List - Leetcode Solution
Companies:
LeetCode: Maximum Twin Sum Of A Linked List Leetcode Solution
Difficulty: Medium
Topics: stack linked-list two-pointers
Problem Statement:
Given a singly linked list, find the maximum twin sum of the linked list. A twin sum is the sum of two consecutive nodes. The maximum twin sum of the linked list is the largest twin sum that can be formed by selecting any two consecutive nodes.
Example 1: Input: 1->2->3->4 Output: 7 Explanation: The maximum twin sum is 3+4=7
Example 2: Input: 5->6->1->2->3 Output: 9 Explanation: The maximum twin sum is 6+3=9
Approach:
We can iterate over the given linked list and calculate the sum of every consecutive pair of nodes. In order to get the maximum twin sum, we need to keep track of the two largest sums seen so far.
To achieve this, we can use two variables, max1 and max2, to store the two highest twin sums seen so far. We can then update them as we iterate through the linked list. If we come across a twin sum that is greater than max1, we can set max2 to max1 and set max1 to the current twin sum. If the current twin sum is greater than max2 but less than max1, we can set max2 to the current twin sum.
After iterating over the entire linked list, we will have the two largest twin sums seen so far in max1 and max2. The maximum twin sum will be the sum of max1 and max2.
Pseudo Code:
max1 = 0 max2 = 0 current = head
while current.next is not null: twin_sum = current.val + current.next.val if twin_sum > max1: max2 = max1 max1 = twin_sum elif twin_sum > max2: max2 = twin_sum current = current.next
return max1 + max2
Complexity Analysis:
Time Complexity: O(n), where n is the number of nodes in the linked list. Space Complexity: O(1), as we are only using two variables to store the maximum twin sums seen so far.
Maximum Twin Sum Of A Linked List Solution Code
1