问题描述
地址: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