198. House Robber

来源:互联网 发布:mysql garela 编辑:程序博客网 时间:2024/06/05 09:29

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

public class Solution {    public static int rob(int[] nums) {            if (nums == null || nums.length == 0)              return 0;          int len = nums.length;          int[] rt = new int[len];          if (len == 1)              return nums[0];          if (len == 2) {              return nums[0] > nums[1] ? nums[0] : nums[1];          }          for (int i = 0; i < len; i++) {              if (i == 0) {                  rt[i] = nums[i];              } else if (i == 1) {                  rt[i] = Math.max(rt[i - 1], nums[i]);              } else {                  rt[i] = Math.max(rt[i - 1], rt[i - 2] + nums[i]);              }          }          return rt[len - 1] > rt[len - 2] ? rt[len - 1] : rt[len - 2];      }  }
原创粉丝点击