From 358388ab29a28484e49d4230ff1610c97026e278 Mon Sep 17 00:00:00 2001 From: SeungHyun Hong Date: Sat, 6 Jul 2024 05:27:50 +0900 Subject: [PATCH] feat: Add solution for LeetCode problem 213 --- house-robber-ii/WhiteHyun.swift | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 house-robber-ii/WhiteHyun.swift diff --git a/house-robber-ii/WhiteHyun.swift b/house-robber-ii/WhiteHyun.swift new file mode 100644 index 000000000..4ba342bf7 --- /dev/null +++ b/house-robber-ii/WhiteHyun.swift @@ -0,0 +1,30 @@ +// +// 213. House Robber II +// https://leetcode.com/problems/house-robber-ii/description/ +// Dale-Study +// +// Created by WhiteHyun on 2024/07/06. +// + +class Solution { + func rob(_ nums: [Int]) -> Int { + if nums.count < 3 { return nums.max()! } + var current = 0 + var previous = 0 + + // 첫 번째 집을 턴 경우 + for element in nums.dropLast() { + (previous, current) = (current, max(element + previous, current)) + } + + var current2 = 0 + var previous2 = 0 + + // 첫 번째 집을 털지 않은 경우 + for element in nums.dropFirst() { + (previous2, current2) = (current2, max(element + previous2, current2)) + } + + return max(current, previous, current2, previous2) + } +}