Solving House Robber problem on LeetCode (step by step approach)

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.
Declare: array (size = n) is the number of gold in every house on street (base index 0)* Start at the house index 0 -> the maximum gold I can rob is array[0] -> asign this to max[0]
* Run to house index 1 -> the maximum gold can rob is max[1] = max(array[0], array[1])
* Run to house index 2 -> max[2] = max(array[0], array[1], array[2], array[0] + array[2])
* max[1] = max(array[0], array[1])
* array[0] + array[2] >= array[2] // (number of gold is > 0)
// --> max[2] = max(max[1], array[0] + array[2])// --> max[2] = max(max[1], max[0] + array[2])
max[n] = max(max[n-2] + array[n], max[n-1])
fun linearRob(array: IntArray):Int{
val intArray = IntArray(array.size) {
-1
}
var max = 0
for(i in array.indices) {
val current = array[i]
val last1 = if(i > 0) intArray[i-1] else 0
val last2 = if(i > 1) intArray[i-2] else 0
val curMax = max(last2 + current, last1)
intArray[i] = curMax
if (curMax > max){
max = curMax
}
}
return max
}
// dp approach
fun dpRob(array: IntArray, tracker: MutableMap<Int, Int>, at: Int):Int {
if(at < 0) return 0
if(!tracker.containsKey(at)) {
val back1 = dpRob(array, tracker, at - 1)
val back2 = dpRob(array, tracker, at - 2)
val value = max(back2 + array[at], back1)
tracker[at] = value
}
return tracker.getOrDefault(at, 0)
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store