-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3394 from drxlx/2130-maximum-twin-sum-of-a-linked…
…-list
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/maximum-twin-sum-of-a-linked-list/ | ||
*/ | ||
|
||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* public var val: Int | ||
* public var next: ListNode? | ||
* public init() { self.val = 0; self.next = nil; } | ||
* public init(_ val: Int) { self.val = val; self.next = nil; } | ||
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } | ||
* } | ||
*/ | ||
class Solution { | ||
func pairSum(_ head: ListNode?) -> Int { | ||
var slow = head | ||
var fast = head | ||
var prev: ListNode? | ||
while fast != nil && fast?.next != nil { | ||
fast = fast?.next?.next | ||
var tmp = slow?.next | ||
slow?.next = prev | ||
prev = slow | ||
slow = tmp | ||
} | ||
var res = 0 | ||
while slow != nil { | ||
res = max(res, prev!.val + slow!.val) | ||
prev = prev?.next | ||
slow = slow?.next | ||
} | ||
return res | ||
} | ||
} |