1- //动态规划的题
2-
31/**
42 * Question:
53 * You are a professional robber planning to rob houses along a street.
1311 *
1412 * /
1513
14+ /**动态规划的题
15+ *
16+ * 思路:
17+ * 本质相当于在一列数组中取出一个或多个不相邻数,使其和最大。求极值的问题。
18+ * 我们维护一个一位数组dp,其中dp[i]表示到i位置时不相邻数能形成的最大和,
19+ * 经过分析,可得到递推公式dp[i] = max(num[i] + dp[i - 2], dp[i - 1])
20+ *
21+ * 分别维护两个变量a和b,然后按奇偶分别来更新a和b,这样就可以保证组成最大和的数字不相邻
22+
23+
1624
1725/**
1826 * @param {number[] } nums
@@ -23,13 +31,13 @@ var rob = function(nums) {
2331 lastRealMax = 0 , //上一轮循环中的真正的最大值
2432 i = nums . length - 1 ;
2533
26- while ( 0 <= i ) { // eg: [2,1 ,1,2 ]
27- var tempLastMaxPV = currMaxPV , //2 0 3
28- realLastMax = lastRealMax ; //0 2 2
29- currMaxPV = realLastMax + nums [ i ] ; //1 3 4
30- lastRealMax = Math . max ( tempLastMaxPV , realLastMax ) ; //2 2 3
34+ while ( 0 <= i ) { // eg: [6,3 ,1,6,1 ]
35+ var tempLastMaxPV = currMaxPV , //0 6 3 7 12
36+ tempLastMax = lastRealMax ; //0 0 6 6 7
37+ currMaxPV = tempLastMax + nums [ i ] ; //6 3 7 12 8
38+ lastRealMax = Math . max ( tempLastMaxPV , tempLastMax ) ; //0 6 6 7 12
3139 i -- ;
3240 }
33- return Math . max ( currMaxPV , lastRealMax ) ; // 4
41+ return Math . max ( currMaxPV , lastRealMax ) ; // 12
3442} ;
3543
0 commit comments