leetcode-53 maximum-subarray

问题描述

地址:http://oj.leetcode.com/problems/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.
翻译:
找到连续的子数组,使得子数组的和最大
比如说给出数组: [-2,1,-3,4,-1,2,1,-5,4],子数组:[4,-1,2,1]有最大的和6

问题解析

这是一道非常经典的动态规划的题目,用到的思路我们在别的动态规划题目中也很常用,以后我们称为”局部最优和全局最优解法“。

基本思路:在每一步,我们维护两个变量,一个是全局最优,就是到当前元素为止最优的解; 一个是局部最优,就是必须包含当前元素的最优的解。

假设我们已知第i步的global[i](全局最优)和local[i](局部最优),那么第i+1步的表达式是:

local[i+1]=Math.max(A[i], local[i]+A[i])
global[i+1]=Math.max(local[i+1],global[i])

解析代码

public int maxSubArray(int[] A) {  
    if(A==null || A.length==0)  
        return 0;  
    int global = A[0];  
    int local = A[0];  
    for(int i=1;i<A.length;i++)  
    {  
        local = Math.max(A[i],local+A[i]);  
        global = Math.max(local,global);  
    }  
    return global;  
}  

参考:http://blog.csdn.net/linhuanmars/article/details/21314059

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值