本文共 542 字,大约阅读时间需要 1 分钟。
/* * 输入一个整形数组,数组里有正数也有负数。 * 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 * 求所有子数组的和的最大值。要求时间复杂度为O(n)。 * 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2, * 因此输出为该子数组的和18。 * 思路:保存当前的和,从做遍历到右,记录最大值,当sum<0的时候值sum为0 * */public class MaxSubArray { public static int maxsubarray(int a[]){ int sum=0; int max=Integer.MIN_VALUE; for(int cur:a){ sum+=cur; if (sum>max) { max=sum; }else if (sum<0) { sum=0; } } return max; } public static void main(String[] args) { int a[]={1,2,10,-9,20,1,-6}; System.out.println(maxsubarray(a)); }}
转载地址:http://comvb.baihongyu.com/