Rob a row of houses along the street, each with a different wealth value, one night to rob the two consecutive will ring the alarm.
Given the value of each family's wealth, how much can you grab?
Ideas
The optimal solution is obtained by dynamic programming.
Key to solving problems: recursive--maxv[i]=max{maxv[i-2]+nums[i], maxv[i-1]};
"Other Code"
intRob (vector<int>&nums) { intn=nums.size (); if(n==0) return 0; if(n==1) returnnums[0]; Vector<int> Maxv (N,0); maxv[0]=nums[0]; maxv[1]=max (nums[0],nums[1]); for(intI=2; i<n; i++) Maxv[i]=max (maxv[i-2]+nums[i], maxv[i-1]); returnmaxv[n-1]; }
"Notes"
The basic idea of dynamic programming, starting with the simplest case, is to compute the current optimal value for each node added.
The code is very easy, the algorithm is difficult to think, the key is recursive type.
OJ Practice 38--t198 House robber