Leetcode DP198.House Robber&53. Maximum Subarray

3 篇文章 0 订阅

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.

不能窃取连续的房子,对于当前的房子来说,有不偷和偷两种状态,比较两种状态的收益,取最大值
解法如下

class Solution {
    public int rob(int[] nums) {
      int prevNo=0;
      int prevYes=0;
      for(int n:nums){
          int temp=prevNo;
          prevNo=Math.max(prevNo,prevYes);//不偷当前房子,求不偷前一个房子和偷前一个房子的最大值
          prevYes=n+temp;//偷当前房子,前一个房子不能偷
      }
        return Math.max(prevNo,prevYes);
    }
}

53. Maximum Subarray

题目要求如下

Find the contiguous subarray within an array (containing at least one
number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous
subarray [4,-1,2,1] has the largest sum = 6.

求连续子序列的和的最大值,同样也是动态规划问题。如果知道了i-1个元素的子序列和的最大值,求i个元素的最大值,最大值有可能还是i-1个元素中产生的子序列的最大值,也有可能是以第i个元素结尾的子序列的和,需要进行比较。以第i个元素结尾的子序列和的最大值,可能是前面以i-1个元素结尾的子序列加上第i个元素,或者是第i个元素本身。
解法如下

class Solution {
    public int maxSubArray(int[] nums) {
        int maxSoFar=nums[0], maxEndingHere=nums[0];
    for (int i=1;i<nums.length;++i){
        maxEndingHere= Math.max(maxEndingHere+nums[i],nums[i]);
        maxSoFar=Math.max(maxSoFar, maxEndingHere); 
    }
    return maxSoFar; 
    }
}

有关动态规划的题目还可以参考
http://blog.csdn.net/srping123/article/details/77371576

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值