同:最大子序和 https://www.cnblogs.com/liujinhui/p/15574312.html
描述
输入一个长度为n的整型数组array,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
方法1:双层循环、暴力求解【运行超时】
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int maxRes = Integer.MIN_VALUE; for(int i = 0; i < array.length; i++) { int sum = 0; for(int j = i; j < array.length; j++) { sum += array[j]; maxRes = Math.max(maxRes, sum); } } return maxRes; } }
方法2:动态规划
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int[] dp = new int[array.length]; dp[0] = array[0]; int maxRes = dp[0]; for(int i = 1; i < array.length; i++) { dp[i] = Math.max(dp[i - 1] + array[i], array[i]); //递推公式 maxRes = Math.max(maxRes, dp[i]); } return maxRes; } }
方法3:动态规划优化
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int maxRes = array[0]; int fi = maxRes; for(int i = 1; i < array.length; i++) { fi = Math.max(fi + array[i], array[i]); maxRes = Math.max(maxRes, fi); } return maxRes; } }
方法4:贪心,sum>0就相加,否则等于当前数
public class Solution { public int FindGreatestSumOfSubArray(int[] array) { int maxRes = array[0]; int sum = 0; for(int i = 0; i < array.length; i++) { if(sum > 0) { sum += array[i]; } else { sum = array[i]; } maxRes = Math.max(maxRes, sum); } return maxRes; } }