Urgent.News

What's breaking now, across thousands of outlets.

Tech

LeetCode #198. House Robber

Problem 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…

A professional thief is attempting to steal from houses arranged in a linear fashion. Each dwelling contains a specific sum of cash; however, the thief cannot rob two neighboring houses on the same night, as their security systems are linked and will immediately alert the authorities if two adjacent properties are broken into concurrently.

The thief is presented with an integer array, nums, which represents the monetary value of each dwelling. The objective is to determine the greatest possible amount of money the thief can amass without triggering the alarm system.

For instance, if the integer array nums is [1,2,3,1], the thief could rob the first house (which contains 1 unit of money) and then proceed to rob the third house (which holds 3 units of money). In this case, the maximum amount of money that can be stolen without triggering the alarm is 1 + 3 = 4.

Similarly, if the integer array nums is [2,7,9,3,1], the thief could rob the first house (2 units of money), followed by the third house (9 units of money), and finally the fifth house (1 unit of money). The maximum amount of money that can be stolen without setting off the alarm in this scenario is 2 + 9 + 1 = 12.

The problem can be solved using a dynamic programming approach. A new array, dp, is created to store the maximum amount of money that can be obtained up to a certain index. The first element in the dp array is assigned the value from the first element in the nums array. The second element in the dp array is set to the maximum value between the first and second elements in the nums array.

The remaining elements in the dp array are populated by taking the maximum value between the previous value in the dp array and the sum of the current value in the nums array and the value before the previous value in the dp array. Once the traversal is complete, the last value in the dp array is returned as the maximum amount of money that can be stolen without alerting the police.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Wednesday 16 September →