最简单的动态规划思路:
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { if(array == null || array.length == 0) { return 0; }
//两个存储变量 int maxSum = Integer.MIN_VALUE; int sum = 0; for (int num : array) { if(sum <= 0) //如果加和小于0,不行(前面+不+无所谓) { sum = num; } else if(sum > 0) { sum = sum + num; //加和大于0,加上这一个 } maxSum = Math.max(maxSum,sum); //如果加和小于之前最大值,先保存之前最大值 } return maxSum; } }