From b58d47d2fa8fb6df21e4205ce31c5d4f12f542ca Mon Sep 17 00:00:00 2001 From: GangBean Date: Fri, 13 Dec 2024 07:21:11 +0900 Subject: [PATCH] solve: house robber --- house-robber/GangBean.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 house-robber/GangBean.java diff --git a/house-robber/GangBean.java b/house-robber/GangBean.java new file mode 100644 index 000000000..c5138dd02 --- /dev/null +++ b/house-robber/GangBean.java @@ -0,0 +1,28 @@ +class Solution { + public int rob(int[] nums) { + /** + r[0] = a[0] + r[1] = max(a[1], r[0]) + r[2] = max(r[1], a[2] + r[0]) + r[3] = max(r[2], a[3] + r[1]) + ... + r[k] = max(r[k-1], a[k] + r[k-2]) O(1) + */ + int[] r = new int[nums.length]; + + for (int i = 0; i < nums.length; i++) { // O(N) + if (i == 0) { + r[i] = nums[i]; + continue; + } + if (i == 1) { + r[i] = Math.max(nums[i], r[i-1]); + continue; + } + r[i] = Math.max(r[i-1], nums[i] + r[i-2]); + } + + return r[nums.length - 1]; + } +} +