개발 일지
198. House Robber (집 도둑) 본문
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;
}
}
}
해설:
털었을때 상황과 털지 않았을때 상황을 제어하여 크기를 비교후 리턴시켜주었습니다.
'코딩 테스트 > LeetCode' 카테고리의 다른 글
55. Jump Game (점프 게임) (0) | 2023.01.09 |
---|---|
733. Flood Fill (홍수 채우기) (0) | 2023.01.09 |
938. Range Sum of BST (BST의 범위 합) (0) | 2022.12.12 |
412. Fizz Buzz (피즈버즈) C# (0) | 2022.11.28 |
374. Guess Number Higher or Lower (숫자가 높은지 낮은지 추측하기) C# (0) | 2022.11.22 |