You is a professional robber planning to rob houses along a street. Each house have a certain amount of money stashed, the only constraint stopping all from robbing each of the them are that Adjac ENT houses have security system connected and it would automatically contact the police if the adjacent houses were bro Keninto on the same night.
Given a list of non-negative integers representing the amount of money in each house, determine the maximum amount of mone Y you can rob tonight without alerting the police.
Error
</pre><pre name= "code" class= "CPP" > int sum=0; if (Nums.size () ==1) return Nums[nums.size ()-1]; if (Nums.size () ==2) { sort (nums.begin (), Nums.end ()); Return Nums[nums.size ()-1]; } Vector<int> nums2=nums; Sort (Nums2.begin (), Nums2.end ()); int l=1000; for (int j=nums2.size () -1;j>= (Nums2.size ()-(Nums2.size ()/2+1)); j--) { int flag=0; for (int i=0;i<nums.size (), i++) {while ((Nums[i]==nums2[j]) && (l!=i) && (l!=i+1) && (l !=i-1)) { sum=sum+nums[i]; l=i; flag=1; } if (flag) break; } } return sum; }};
Correct answer
Class Solution {public: int Rob (vector<int>& nums) {//DP thought int n=nums.size (); if (n==0) return 0; if (n==1) return nums[0]; Vector<int> m (n,0); <strong><span style= "color: #006600;" >//must be initialized, otherwise out of run time //Do not initialize the vector, is empty, cannot call nums[i]----guess the probable cause </span></strong>
The subscript operation of a vector object can be used to access an already existing element,
<span style= "font-family:arial, Helvetica, Sans-serif;" >//cannot be used to add elements, add elements push_back () or initialize </span></strong></span>
M[0]=nums[0]; M[1]=max (Nums[0],nums[1]); for (int i=2;i<n;i++) { M[i]=max (m[i-1],m[i-2]+nums[i]); } return m[n-1];} ;
Leetcode 198. House robber