标签:style blog http color io ar for 问题 div
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
.
Answer:
这应该是一个动态规划问题,但是没有看过动态规划的算法。
解答的思路就是,如果新的字串更大的话,新的字串肯定包含新的节点,既然包含新的节点,那么上一节点也肯定在其中(或者肯定不在其中)。
public class Solution { public int maxSubArray(int[] A) { int maxSubSum = Integer.MIN_VALUE; int maxNowNode = 0; if (A.length == 0) return 0; for (int i=0; i<A.length; i++) { maxNowNode = maxNowNode>0? maxNowNode + A[i] : A[i]; maxSubSum = Math.max(maxSubSum, maxNowNode); } return maxSubSum; } }
标签:style blog http color io ar for 问题 div
原文地址:http://www.cnblogs.com/yuhaos/p/3943944.html