Leetcode 198: House Robber

来源:互联网 发布:淘宝联盟的导购推广位 编辑:程序博客网 时间:2024/04/28 05:09

House Robber
Total Accepted: 642 Total Submissions: 2562

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.

[分析]
维持两个数组, 一个是包含最后一个字符的最大值, 一个是不包含最后一个字符的最大值. 更新两个数组, 最后求 max(d[n-1], b[n-1])即可.

public class Solution {    public int rob(int[] num) {        //   31 23 9 13 49 1 0        //   0  0 0 0        if(num==null || num.length==0) return 0;        int n = num.length;        int [] b = new int[n]; //include last element;        int [] d = new int[n]; //exclude last element;        b[0] = num[0];        d[0] = 0;        for(int i=1; i<n; i++) {            b[i] = d[i-1] + num[i];            d[i] = Math.max(b[i-1], d[i-1]);        }        return Math.max(d[n-1], b[n-1]);    }}
0 0
原创粉丝点击