[LeetCode 198]House Robber

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.


Solution:

every step result is based on previous one, could use DP.

take = nums[i] + nontake[i-1]

nontake = maxprofit

maxprofit = Math.max(take, nontake)


public int rob(int[] nums) {
        int take = 0;
        int nontake = 0;
        int maxprofit = 0;
        for(int i=0;i<nums.length;i++){
            take = nums[i] + nontake;
            nontake = maxprofit;
            maxprofit = Math.max(take, nontake);
        }
        return maxprofit;
    }



你可能感兴趣的:(LeetCode,dp)