.Zzumbong

[leetCode/JS] 198. House Robber ๋ณธ๋ฌธ

coding test/leetCode

[leetCode/JS] 198. House Robber

์ญ˜๋ด‰ 2022. 12. 14. 09:44

๋‚œ์ด๋„ [ ๐Ÿค” ] Medium

 

๋ฌธ์ œ ์„ค๋ช…

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.

๋‚œ ํ”„๋กœํŽ˜์…”๋„ ๋„๋‘‘์ด๋‹ค.
๊ฐ ์ง‘์— ์žˆ๋Š” ๋ˆ์ด array nums๋กœ ์ž…๋ ฅ๋˜๋Š”๋ฐ, ๊ทผ์ ‘ํ•œ ์ง‘์„ ํ„ธ๋ฉด ์•ˆ๋œ๋‹ค.
์ตœ๋Œ€ํ•œ ํ„ธ ์ˆ˜ ์žˆ๋Š” ๋ˆ์€ ์–ผ๋งˆ์ธ๊ฐ€?

 

์ž…์ถœ๋ ฅ ์˜ˆ

Example 1:

Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

 

Example 2:

Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

 

Constraints

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

 


 

๋‚ด ์†”๋ฃจ์…˜

  • ๋ญ”๊ฐ€ ์กฐ๊ฑด์ด ์žˆ์œผ๋ฉด์„œ ์ตœ๋Œ€ ์–ผ๋งˆ์ธ๊ฐ€? ์ตœ์†Œ ์–ผ๋งˆ์ธ๊ฐ€? ํ•˜๋ฉด DP๋ถ€ํ„ฐ ์ƒ๊ฐํ•ด์•ผํ•˜๋”๋ผ.. ์–ด๋ ต
  • ๋งŒ์•ฝ [3, 1, 1, 9] ๋ผ๋ฉด ์ฒซ์ง‘์€ 3์„ ๊ณจ๋ผ์•ผํ•œ๋‹ค. ๊ทธ๋Ÿฌ๋ฏ€๋กœ ์ฒซ ์ง‘์€ Math.max(nums[0], nums[1])๋กœ ๊ณ ๋ฅธ๋‹ค.
  • Math.max(nuns[i-2] + nums[i], nums[i-1]) ๋กœ ์ง€๊ธˆ ์ง‘ + ์ด์ „์ด์ „์ง‘ or ์ด์ „์ง‘ ์ค‘ ๊ณ ๋ฅด๋Š” ๊ฒƒ์ด ๊ธฐ๋ณธ๋ฃฐ์ด๋‹ค.
  • ๋งจ ์ฒ˜์Œ if์—์„œ length๊ฐ€ 1 ๋˜๋Š” 2๋Š” ๊ทธ๋ƒฅ ํฐ ๊ฐ’์„ ๋ฆฌํ„ดํ•˜๋ฉด ๋œ๋‹ค.
var rob = function(nums) {
  if(nums.length < 3) return Math.max(...nums);
  let prevPrev = nums[0];
  let prev = Math.max(nums[1], nums[0]);
  for(let i = 2; i < nums.length; i++) {
    const max = Math.max(nums[i] + prevPrev, prev);
    prevPrev = prev;
    prev = max;
  }
  return prev
};

 

๊ฐ์ƒํ‰

  • DP๊ฐ€ ์•ฝ์ ์ธ ๊ฒƒ์ด ๋ถ„๋ช…ํ•˜๋‹ค. DP ๊ฐ™์€๋ฐ ํ•˜๋ฉด์„œ ์–ด๋–ป๊ฒŒ ๋งŒ๋“ค์ง€~ ๊ฐ€์ง€๊ณ  30๋ถ„ ๋‚ด๋‚ด ์”จ๋ฆ„ํ–ˆ๋‹ค.
  • ๊ฒฐ๊ตญ ํ˜ผ์ž์„œ ํ’€๊ธฐ๋Š” ํฌ๊ธฐํ•˜๊ณ  DP ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ตฌ๊ธ€๋งํ•˜๋ฉฐ ํ˜ผ์ž ์ƒ์‡ผ๋ฅผ ํ–ˆ๋‹ค.
  • ํ•˜๋ฃจ ์ข…์ผ ๊ฑธ๋ฆฌ๋ป”ํ–ˆ๋‹ค. ์ฅ์—”์žฅ
  • DP๋ฌธ์ œ๋ฅผ ํ•˜๋‚˜ ๋” ํ’€์–ด๋ณด์ž.

'coding test > leetCode' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[leetCode/JS] 1143. Longest Common Subsequence  (0) 2022.12.15
[leetCode/JS] 152. Maximum Product Subarray  (0) 2022.12.14
[leetCode/JS] 931. Minimum Falling Path Sum  (0) 2022.12.13
[leetCode/JS] 70. Climbing Stairs  (0) 2022.12.12
[leetCode/JS] 124. Binary Tree Maximum Path Sum  (0) 2022.12.11
0 Comments
๋Œ“๊ธ€์“ฐ๊ธฐ ํผ