zoukankan      html  css  js  c++  java
  • leetcode 213. House Robber II

    You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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: [2,3,2]
    Output: 3
    Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
                 because they are adjacent houses.
    

    Example 2:

    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.

    题目大意:房子以圆形布置,小偷同时偷相邻的房屋就会报警。求在不报警的前提下,能偷到的最多钱数。

    分析:由于圆形,第0家和第n家(最后一家)不能同时被偷,因此分两种情况转化为房子呈直线布置的情况就好了(0, ..., n - 1)和(1, ..., n)

     1 class Solution {
     2 public:
     3     int rob(vector<int>& nums) {
     4         int len = nums.size();
     5         if (len == 0)
     6             return 0;
     7         if (len == 1)
     8             return nums[0];
     9         return max(robOriginal(nums, 0, len - 2, len), robOriginal(nums, 1, len - 1, len));
    10     }
    11 private:
    12     int robOriginal(vector<int> nums, int l, int r, int len) {
    13         int prev = 0, cur = 0;
    14         for (int i = l; i <= r; i++) {
    15             int temp = max(cur, prev + nums[i]);
    16             prev = cur;
    17             cur = temp;
    18         }
    19         return cur;
    20     }
    21 };
  • 相关阅读:
    【重磅资料】ArchSummit全球架构师峰会·2019华为云技术专场资料下载
    00074_Array类
    JSP中RequestDispatcher的用法
    最近6个月的感受
    java大文件(百M以上)的上传下载功能
    java大文件(百M以上)的上传下载解决方案
    java大文件(百M以上)的上传下载方案
    java大文件(百M以上)的上传下载技术
    wangEditor
    umeditor
  • 原文地址:https://www.cnblogs.com/qinduanyinghua/p/11467090.html
Copyright © 2011-2022 走看看