Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Create 2130-maximum-twin-sum-of-a-linked-list.swift #3394

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions swift/2130-maximum-twin-sum-of-a-linked-list.swift
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
}
}