-
198. House RobberAlgorithm/java tip 2021. 3. 23. 23:53
leetcode.com/problems/house-robber/
House Robber - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
class Solution { // dp public int rob(int[] nums) { int[][] dp = new int[2][nums.length]; dp[0][0] = nums[0]; dp[1][0] = 0; for(int i=1; i<nums.length; i++) { dp[0][i] = dp[1][i-1] + nums[i]; dp[1][i] = Math.max(dp[0][i-1], dp[1][i-1]); } return Math.max(dp[0][nums.length-1], dp[1][nums.length-1]); } }
JAVA DP Solution, O(n) runtime and O(1) space, with inline comment - LeetCode Discuss
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
public int rob(int[] num) { int rob = 0; //max monney can get if rob current house int notrob = 0; //max money can get if not rob current house for(int i=0; i<num.length; i++) { int currob = notrob + num[i]; //if rob current value, previous house must not be robbed notrob = Math.max(notrob, rob); //if not rob ith house, take the max value of robbed (i-1)th house and not rob (i-1)th house rob = currob; } return Math.max(rob, notrob); }
'Algorithm > java tip' 카테고리의 다른 글
347. Top K Frequent Elements (0) 2021.03.24 230. Kth Smallest Element in a BST (0) 2021.03.24 1387. Sort Integers by The Power Value (0) 2021.03.21 1557. Minimum Number of Vertices to Reach All Nodes (0) 2021.03.20 797. All Paths From Source to Target (0) 2021.03.20