Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

198. House Robber (집 도둑) 본문

코딩 테스트/LeetCode

198. House Robber (집 도둑)

포카리tea 2022. 12. 23. 01:02

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

 

당신은 거리를 따라 집을 털려는 전문 강도입니다. 각 집에는 일정 금액의 돈이 숨겨져 있습니다. 각각의 집을 강탈하지 못하도록 막는 유일한 제약은 인접한 집에 보안 시스템이 연결되어 있고 같은 밤에 두 개의 인접한 집이 침입한 경우에는 자동으로 경찰에 연락이 됩니다.

 

각 집의 금액을 나타내는 정수 배열 숫자가 주어지면 오늘 밤 경찰에 알리지 않고 훔칠 수 있는 최대 금액을 반환하세요.

예시 1:

입력: nums = [1, 2, 3, 1]
출력: 4
설명: 1번 집(돈 = 1)을 털고 3번 집(돈 = 3)을 텁니다.
털 수 있는 총 금액 = 1 + 3 = 4

예시 2:

입력: nums = [2, 7, 9, 3, 1]
출력: 12
설명: 1번 집(돈 = 2)을 털고, 3번 집(돈 = 9)을 털고 5번 집(돈 = 1)을 텁니다.
털 수 있는 총 금액 = 2 + 9 + 1 = 12

 

조건:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

정답:

public class Solution
{
    public int Rob(int[] nums)
    {
        int Plus = 0;
        int skip = 0;

        foreach (int item in nums)
        {
            int temp = Plus;
            Plus = item + skip;
            if (temp > skip)
            {
                skip = temp;
            }
        }

        if (Plus > skip)
        {
            return Plus;
        }
        else
        {
            return skip;
        }
    }
}

해설: 

털었을때 상황과 털지 않았을때 상황을 제어하여 크기를 비교후 리턴시켜주었습니다.