Skip to content

Latest commit

 

History

History
107 lines (91 loc) · 2.84 KB

198. House Robber.md

File metadata and controls

107 lines (91 loc) · 2.84 KB

leetcode Daily Challenge on September 14th, 2020.


Difficulty : Easy

Related Topics : Dynamic Programming


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 system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

Solution

  • mine
    • Java
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 37.2 MB, less than 5.26% of Java online submissions

        // O(N)time
        // O(1)space
        public int rob(int[] nums) {
            if(nums == null || nums.length == 0){
                return 0;
            }
            int len = nums.length;
            if(len == 1){
                return nums[0];
            }
            for(int i = 2; i < len; i++){
                int t = 0;
                if(i > 2){
                    t = nums[i - 3];
                }
                nums[i] = nums[i] + Math.max(nums[i-2], t);
            }
            return Math.max(nums[len-1],nums[len - 2]);
        }
        
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 39.3 MB, less than 5.12% of Java online submissions

        // O(N)time
        // O(1)space
        public int rob(int[] nums) {
            int cur = 0, pre = 0;
            for(int num : nums){
                int t = pre + num;
                pre = Math.max(cur, pre);
                cur = t;
            }
            return Math.max(cur, pre);
        }
        

  • the most votes
  • Runtime: 0 ms, faster than 100.00%, Memory Usage: 36.9 MB, less than 5.26% of Java online submissions
// O(N)time
// O(1)space
public int rob(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    int length = nums.length;
    if (length == 1) {
        return nums[0];
    }
    int first = nums[0], second = Math.max(nums[0], nums[1]);
    for (int i = 2; i < length; i++) {
        int temp = second;
        second = Math.max(first + nums[i], second);
        first = temp;
    }
    return second;
}