Created
July 18, 2023 21:23
-
-
Save optimistiks/5f9177e6e97c3beddf6cfcbde759b9e1 to your computer and use it in GitHub Desktop.
A professional robber plans to rob some houses along a street. These houses are arranged in a circle, which means that the first and the last house are neighbors. The robber cannot rob adjacent houses because they have security alarms installed. Following the constraints mentioned above and given an integer array money representing the amount of…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function houseRobber(money) { | |
| return Math.max( | |
| calcMax(money, 0, money.length - 1), | |
| calcMax(money, 1, money.length) | |
| ); | |
| } | |
| function calcMax(money, from, to) { | |
| const dp = []; | |
| for (let i = from; i < to; ++i) { | |
| dp[i] = Math.max(money[i] + (dp[i - 2] ?? 0), dp[i - 1] ?? 0); | |
| } | |
| return Math.max(...dp.filter((num) => num != null)); | |
| } | |
| export { houseRobber }; | |
| // tc: O(n) | |
| // sc: O(n) (can be improved to O(1) by using 2 variables instead of 2 arrays) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment