摘要:但是任何臨近的兩個房子被偷就會觸發警報。要求我們求出在不觸發警報的情況下偷到的最多的錢。每個房子里的錢通過輸入的數組表示。
題目詳情
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.題目的意思是,我們是一個江洋大盜~現在我們要去偷整條街的房子,每個房子里有一定的錢。但是任何臨近的兩個房子被偷就會觸發警報。要求我們求出在不觸發警報的情況下偷到的最多的錢。每個房子里的錢通過輸入的int數組表示。
動態規劃問題
對于每一個房子,我們有偷/不偷兩種選擇
因此我們聲明兩個變量prevNo和prevYes分別保存,我沒偷/偷了當前房子的情況下,目前為止偷的最多的錢數。
如果想偷當前房子,那么要求我們并沒有偷前一個房子,所以用前一個房子的prevNo值和當前房子的錢數相加。
如果不偷當前房子,那我們可以取前一個房子的prevNo值和prevYes值中較大的那個。
解法public int rob(int[] nums) { int prevNo = 0; int prevYes = 0; for(int n: nums){ int temp = prevNo; prevNo = Math.max(prevNo, prevYes); prevYes = temp+n; } return Math.max(prevNo, prevYes); }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/71012.html
摘要:你不能連著偷兩家因為這樣會觸發警報系統?,F在有一個數組存放著每一家中的可偷金額,問可以偷的最大金額為多少這里考驗了動態編程的思想。動態編程要求我們將問題一般化,然后再找到初始情況開始這個由一般到特殊的計算過程。 House Robber I You are a professional robber planning to rob houses along a street. Each...
摘要:注意對邊界條件的判斷,是否非空,是否長度為 House Robber I Problem 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 y...
摘要:動態規劃復雜度時間空間思路一般來說,給定一個規則,讓我們求任意狀態下的解,都是用動態規劃。另外我們可以做一點優化,本來我們是要用一個數組來保存之前的結果的。所以我們分別算出這兩個條件下的最大收益,然后取更大的就行了??梢詮陀玫拇a。 House Robber I You are a professional robber planning to rob houses along a ...
摘要:復雜度思路對于每一個位置來說,考慮兩種情況分別對和再進行計算。用對已經計算過的進行保留,避免重復計算。 LeetCode[337] House Robber III The thief has found himself a new place for his thievery again. There is only one entrance to this area, calle...
摘要:因為取了隊首就不能取隊尾,所以對數組循環兩次,一個從取到,一個從取到,比較兩次循環后隊尾元素,取較大者。注意,要先討論當原數組位數小于時的情況。 Problem After robbing those houses on that street, the thief has found himself a new place for his thievery so that he wi...
閱讀 2864·2021-11-16 11:55
閱讀 2608·2021-09-29 09:34
閱讀 3405·2021-09-01 14:21
閱讀 3753·2019-08-29 12:36
閱讀 697·2019-08-26 10:55
閱讀 3959·2019-08-26 10:20
閱讀 1026·2019-08-23 18:19
閱讀 1194·2019-08-23 17:56