198. House Robber (Easy)

https://leetcode.com/problems/house-robber/

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.

Solutions

class Solution {

    // Another dynamic program problem.

    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;

        int[] track = new int[len + 1];
        Arrays.fill(track, -1);
        track[len - 1] = nums[len - 1];
        track[len] = 0;

        for (int i = len - 2; i >= 0; i--) {
            // two options:

            // 1. rob ith house and ignore (i+1)th house. Then jump to house (i+2) and decide what to do,
            // you can either rob or just ignore.

            // 2. ignore ith house and take the wealth of house (i+1). On house you can decide the best choice.
            track[i] = Math.max(track[i + 1], nums[i] + track[i + 2]);
        }

        int max = 0;
        for (int i = 0; i < len; i++) {
            max = Math.max(max, track[i]);
        }

        return max;
    }
}

Incorrect Solutions

class Solution {

    // Time Limit Exceeded

    // We also can use recursion technique to get over this problem.

    int max = -1;
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;

        recurse(nums, 0, true, 0);

        return max;
    }

    private void recurse(int[] nums, int i, boolean canRob, int value) {
        if (value > max) {
            max = value;
        }

        if (i >= nums.length) {
            return;
        }

        if (canRob) {
            recurse(nums, i + 1, false, value + nums[i]);
        }

        recurse(nums, i + 1, true, value);
    }
}

References

Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2020-03-21 14:48:56

results matching ""

    No results matching ""