zoukankan      html  css  js  c++  java
  • 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 are arranged 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.

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    Runtime: 0ms

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int n = nums.size();
     5         if(n == 0) return 0;
     6         if(n == 1) return nums[0];
     7         if(n == 2) return max(nums[0], nums[1]);
     8         
     9         int *dp1 = new int[n];
    10         dp1[0] = nums[0];
    11         dp1[1] = nums[0];
    12         //rub the first house
    13         for(int i = 2; i < n - 1; i++){
    14             dp1[i] = max(dp1[i -2] + nums[i], dp1[i - 1]);
    15         }
    16         dp1[n - 1] = dp1[n - 2];
    17         
    18         //do not rub the first house
    19         int *dp2 = new int[n];
    20         dp2[0] = 0;
    21         dp2[1] = nums[1];
    22         for(int i = 2; i < n; i++){
    23             dp2[i] = max(dp2[i - 2] + nums[i], dp2[i - 1]);
    24         }
    25         
    26         return max(dp1[n - 1], dp2[n -1]);
    27     }
    28 };
  • 相关阅读:
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业03
    C语言第二周作业
    C语言第一周课程作业
    C语言期末总结
    第一次作业
    C语言I博客作业09
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4809043.html
Copyright © 2011-2022 走看看