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
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
此题是典型的动态规划类型题目,即全局最优和局部最优解法。每一步,维护两个变量,一个是全局最优,就是到当前元素为止最优的解,一个是局部最优,就是必须包含当前元素的最优的解。假设我们已知第i步的global[i](全局最优)和local[i](局部最优),那么第i+1步的表达式是:
local[i+1]=Math.max(A[i], local[i]+A[i]),
就是局部最优是一定要包含当前元素,所以不然就是上一步的局部最优local[i]+当前元素A[i](因为local[i]一定包含第i个元素,所以不违反条件),但是如果local[i]是负的,那么加上他还不如不加,所以不然就是直接用A[i];
global[i+1]=Math(local[i+1],global[i]),
有了当前一步的局部最优,那么全局最优就是当前的局部最优或者还是原来的全局最优(所有情况都会被涵盖进来,因为最优的解如果不包含当前元素,那么前面全局最优会被维护在当前全局最优里面,如果包含当前元素,那么就是这个局部最优)。
代码: