KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (486)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • Git (5)
    • Web (24)
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • ETC (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)
    • PS (431)
      • 백준 (187)
      • Programmers (104)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • 제코베 JS 100제
  • 백준
  • js
  • programmers
  • 문자열
  • Level 0
  • recursion
  • Level 1
  • Level1
  • 정렬
  • 다이나믹 프로그래밍
  • 수학
  • tree
  • C
  • 그래프
  • Level 2
  • LeetCode
  • C++
  • string
  • codeup

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Dynamic Programming / 198번 / House Robber / JS

2023. 5. 14. 19:13

< 문제 바로가기 >

 

House Robber - LeetCode

Can you solve this real interview question? 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 ho

leetcode.com

 

< 문제 간단설명 >

도둑이 연속해서 인접한 두 집을 연속해서 도둑질하면 경찰에게 걸린다. 따라서 인접한 두 집을 연속해서 도둑질 하지 않는다고 할 때 가장 많이 도둑질 했을때의 돈을 반환한다.

 

/**
 * @param {number[]} nums
 * @return {number}
 */
var rob = function (nums) {
  // 연속해서 두 집을 훔칠 수 없기 때문에 가장 큰 값 반환
  if (nums.length <= 2) {
    return Math.max(...nums);
  }

  // dp[index] = index 번 째 집을 도둑질 했을 때 얻을 수 있는 최댓값
  let dp = Array.from({ length: nums.length }, () => 0);

  dp[0] = nums[0]; // 0번째 집을 털었을 때 얻을 수 있는 최댓값은 0번째만 털 수 있음
  dp[1] = nums[1]; // 1번째 집은 0번째 집을 털 수 없으므로 1번째 집만 털었을 때 최댓값
  dp[2] = dp[0] + nums[2]; // 2번째 집은 1번째 집을 털 수 없으므로 0번째 값과 더해줌

  // i번째는 i-1번째와 연속으로 털 수 없기 때문에,
  // i-2와 i-3번째 중 최댓값과 i번째 값을 더해줌
  for (let i = 3; i < nums.length; i += 1) {
    dp[i] = Math.max(dp[i - 3], dp[i - 2]) + nums[i];
  }

  return Math.max(...dp);
};
저작자표시 (새창열림)

'PS > LeetCode' 카테고리의 다른 글

LeetCode / Dynamic Programming / 416번 / Partition Equal Subset Sum / JS  (0) 2023.05.14
LeetCode / Dynamic Programming / 322번 / Coin Change / JS  (0) 2023.05.14
LeetCode / Graph / 210번 / Course Schedule II / JS  (0) 2023.05.14
LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS  (0) 2023.04.29
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Dynamic Programming / 416번 / Partition Equal Subset Sum / JS
    • LeetCode / Dynamic Programming / 322번 / Coin Change / JS
    • LeetCode / Graph / 210번 / Course Schedule II / JS
    • LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS
    KimMinJun
    KimMinJun

    티스토리툴바