From 13eb3352b848bfd139ab29dcf46eb331ad0438c4 Mon Sep 17 00:00:00 2001 From: Peter Chen Date: Sat, 6 Sep 2025 09:33:36 +0800 Subject: [PATCH] Add unit tests for the "House Robber" problem. --- .../com/leetcode/medium}/HouseRobber198.java | 18 ++++------ .../leetcode/medium/HouseRobber198Test.java | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+), 11 deletions(-) rename src/{ => main/java/com/leetcode/medium}/HouseRobber198.java (60%) create mode 100644 src/test/java/com/leetcode/medium/HouseRobber198Test.java diff --git a/src/HouseRobber198.java b/src/main/java/com/leetcode/medium/HouseRobber198.java similarity index 60% rename from src/HouseRobber198.java rename to src/main/java/com/leetcode/medium/HouseRobber198.java index 32503e4..07acbf7 100644 --- a/src/HouseRobber198.java +++ b/src/main/java/com/leetcode/medium/HouseRobber198.java @@ -1,11 +1,13 @@ -// Array, Dynamic Programming +// Tags: Dynamic Programming +package com.leetcode.medium; + public class HouseRobber198 { /* - Time Complexity: O(N) since we have a loop from 0...nums.length-1, + Time complexity: O(N) since we have a loop from 0...nums.length-1, and we simply use the pre-calculated values of our dynamic programming table for calculating the current value in the table which is a constant time operation. - Space Complexity: O(N) which is used by the table. + Space complexity: O(N) which is used by the table. */ public int robTabulation(int[] nums) { if (nums.length == 1) { @@ -17,15 +19,9 @@ public int robTabulation(int[] nums) { int[] dp = new int[nums.length]; dp[0] = nums[0]; dp[1] = Math.max(nums[0], nums[1]); - for (int i = 2; i < dp.length; i++) { + for (int i = 2; i < nums.length; i++) { dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); } - return dp[dp.length - 1]; - } - - public static void main(String[] args) { - int[] nums = new int[]{1, 2, 3, 1}; - System.out.println(new HouseRobber198().robTabulation(nums)); - // 4 + return dp[nums.length - 1]; } } diff --git a/src/test/java/com/leetcode/medium/HouseRobber198Test.java b/src/test/java/com/leetcode/medium/HouseRobber198Test.java new file mode 100644 index 0000000..d1c850d --- /dev/null +++ b/src/test/java/com/leetcode/medium/HouseRobber198Test.java @@ -0,0 +1,35 @@ +package com.leetcode.medium; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class HouseRobber198Test { + private HouseRobber198 solution; + + @BeforeEach + void setUp() { + solution = new HouseRobber198(); + } + + @Test + void testRobTabulation_Example1() { + int[] nums = {1, 2, 3, 1}; + int expected = 4; + + int result = solution.robTabulation(nums); + + assertEquals(expected, result); + } + + @Test + void testRobTabulation_Example2() { + int[] nums = {2, 7, 9, 3, 1}; + int expected = 12; + + int result = solution.robTabulation(nums); + + assertEquals(expected, result); + } +}