最大子序列和问题

给定(有可能有负数)正数A1,A2,...An,求Ai,Ai+1,...Aj的最大值(i>=1,j>=i,j<=n)。(方便起见,如果索引正数均为负数,则最大子序列和为0)

JAVA实现源码如如下:

public class MaxSubSum {
	public static int maxSubSum(int[] a) {
		int maxSum = 0, thisSum = 0;
		for (int i = 0, length = a.length; i < length; i++) {
			thisSum += a[i];
			if (thisSum > maxSum)
				maxSum = thisSum;
			else if (thisSum < 0)
				thisSum = 0;
		}
		return maxSum;
	}

	public static void main(String[] args) {
		int[] a = { -1, 0, 2, 4, 3, -9, 7, 2, 1, -5, 2 };
		System.out.println(maxSubSum(a));
	}
}


你可能感兴趣的:(java,算法)