198 House Robber

来源:互联网 发布:淘宝密码怎么修改 编辑:程序博客网 时间:2024/04/30 04:28

Leetcode198:

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.

这是一道典型的线性规划问题,假设有n个房子,编号0~n-1,令抢劫第i个房子时已经抢到的钱最多,则:

抢劫第i个房子   f(i) = num[i] + g(i+1)

不抢劫第i个房子   g(i) = max( f(i) , g(i) )

class Solution {public:int rob(vector<int> &num) {int f = 0, g = 0, pref = 0, preg = 0, s = 0;for (int i = num.size() - 1; i >= 0;i--){f = preg + num[i];g = max(pref, preg);pref = f;preg = g;}return max(f, g);}};


0 0
原创粉丝点击