zoukankan      html  css  js  c++  java
  • [leedcode 213] House Robber II

    Note: This is an extension of House Robber.

    After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place arearranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

    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.

    public class Solution {
        public int rob(int[] nums) {
            //遍历两遍,第一遍包括头结点,不包括尾节点;第二遍包括尾节点,不包括头结点,求二者最大值
            if(nums.length==0) return 0;
            if(nums.length==1) return nums[0];//只有一个节点时,需特殊判断
            int unrob=0;
            int rob=0;
            for(int i=0;i<nums.length-1;i++){
                int temp=rob;
                rob=nums[i]+unrob;
                unrob=Math.max(unrob,temp);
            }
            int res1=Math.max(rob,unrob);
             unrob=0;
             rob=0;
            for(int i=1;i<nums.length;i++){
                int temp=rob;
                rob=nums[i]+unrob;
                unrob=Math.max(temp,unrob);
            }
            int res2=Math.max(rob,unrob);
            return Math.max(res1,res2);
        }
    }
  • 相关阅读:
    组合数学
    gcd和lcm
    快速幂
    线性求逆元
    5月月赛(* ̄︿ ̄)
    通往奥格瑞玛的道路
    Dijkstra学习笔记
    动态规划笔记(2)
    美军战略指导:《维持美国的世界领导力:21世纪国防的优先事项》
    ACM/ICPC2016沈阳网络赛(不完全)解题报告
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4708998.html
Copyright © 2011-2022 走看看