Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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];
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/leetcode/medium/HouseRobber198Test.java
Original file line number Diff line number Diff line change
@@ -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);
}
}