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.
跟之前爬樓梯一樣
我只要把之前算好的拿來用就好
假設房子價錢如下
1 4 7 1 8 13 6 22 6 8 33 123 55]
我們再去每搶一個房子會得到的價錢weight
weight[i+1]= weight[i+1-2]>= weight[i+1-3]? weight[i+1-2]+nums[i]:weight[i+1-3]+nums[i];
是看上上一棟跟上上上一棟哪個多(槍棟相鄰不能算)
0 1 4 8 5 16 21 22 43 28 51 76 174 131
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | int rob(int* nums, int numsSize) { if(numsSize<=1)return nums[0]; else if(numsSize==2)return nums[0]>=nums[1]? nums[0]:nums[1]; int weight[numsSize+1]; weight[0]=0; weight[1]=nums[0]; weight[2]=nums[1]; int max=weight[1]>=weight[2]? weight[1]:weight[2]; for(int i=2;i<numsSize;i++){ weight[i+1]= weight[i+1-2]>= weight[i+1-3]? weight[i+1-2]+nums[i]:weight[i+1-3]+nums[i]; max = max>weight[i+1]? max:weight[i+1]; } //for(int i =0;i<numsSize+1;i++)printf("%d ",weight[i]); return max; } |
沒有留言:
張貼留言