Skip to content

Commit 9067fad

Browse files
committedJan 13, 2025
Add solution #2130
1 parent f0b143b commit 9067fad

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@
393393
2114|[Maximum Number of Words Found in Sentences](./2114-maximum-number-of-words-found-in-sentences.js)|Easy|
394394
2116|[Check if a Parentheses String Can Be Valid](./2116-check-if-a-parentheses-string-can-be-valid.js)|Medium|
395395
2129|[Capitalize the Title](./2129-capitalize-the-title.js)|Easy|
396+
2130|[Maximum Twin Sum of a Linked List](./2130-maximum-twin-sum-of-a-linked-list.js)|Medium|
396397
2154|[Keep Multiplying Found Values by Two](./2154-keep-multiplying-found-values-by-two.js)|Easy|
397398
2185|[Counting Words With a Given Prefix](./2185-counting-words-with-a-given-prefix.js)|Easy|
398399
2215|[Find the Difference of Two Arrays](./2215-find-the-difference-of-two-arrays.js)|Easy|
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 2130. Maximum Twin Sum of a Linked List
3+
* https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/
4+
* Difficulty: Medium
5+
*
6+
* In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known
7+
* as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1.
8+
*
9+
* For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These
10+
* are the only nodes with twins for n = 4.
11+
*
12+
* The twin sum is defined as the sum of a node and its twin.
13+
*
14+
* Given the head of a linked list with even length, return the maximum twin sum of the linked list.
15+
*/
16+
17+
/**
18+
* Definition for singly-linked list.
19+
* function ListNode(val, next) {
20+
* this.val = (val===undefined ? 0 : val)
21+
* this.next = (next===undefined ? null : next)
22+
* }
23+
*/
24+
/**
25+
* @param {ListNode} head
26+
* @return {number}
27+
*/
28+
var pairSum = function(head) {
29+
const stack = [];
30+
while (head) {
31+
stack.push(head.val);
32+
head = head.next;
33+
}
34+
35+
let max = 0;
36+
for (let i = 0; i < stack.length; i++) {
37+
max = Math.max(max, stack[i] + stack[stack.length - 1 - i]);
38+
}
39+
40+
return max;
41+
};

0 commit comments

Comments
 (0)
Please sign in to comment.