PS/LeetCode

[Kotlin] LeetCode 2130 : maximum-twin-sum-of-a-linked-list

뱃싸공 2022. 11. 30. 11:28
 

Maximum Twin Sum of a Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

연결 리스트가 주어졌을때, twin 노드를 더했을때 가장 큰 값을 구하라고 합니다.
간단하게 문제를 해석해보면, 주어진 연결리스트를 list1이라고 두고, list1을 뒤집은 연결 리스트를 list2라고 정의합니다. 이제 리스트를 순환하면서 list1[i] + list2[i] 의 값을 모두 구하고, 이중 최댓값을 구하면 됩니다.

시간복잡도는 배열의 길이가 N일때 O(3N)이 소요되므로 O(N)으로 잡을 수 있습니다.

/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
import kotlin.math.max

class Solution {
    fun pairSum(head: ListNode?): Int {
        
        var list1 = getList(head)
        var current = reverse(head)
        var list2 = getList(current)
        
        var answer : Int = 0
        for(i in 0..list1.size-1) {
            answer = max((getValue(list1, i) + getValue(list2, i)), answer)
        }
        return answer
    }
    
    fun reverse(head : ListNode?) : ListNode? {
        var prev : ListNode? = null
        var current : ListNode? = head
        var next : ListNode? = null
        
        while(isNotNull(current)) {
            next = current?.next
            current?.next = prev
            prev = current
            current = next
        }
        return prev
    }
    
    fun isNotNull(node : ListNode?) : Boolean = (node != null)
    
    fun getList(head : ListNode?) : MutableList<Int?> {
        var list : MutableList<Int?> = mutableListOf()
        var node : ListNode? = head
        while(isNotNull(node)) {
            list.add(node?.`val`)
            node = node?.next
        }
        return list
    }
    
    fun getValue(list : MutableList<Int?>, index : Int) : Int = list[index] ?: 0
}