您的位置:首页 > 编程语言 > Java开发

java之连续子数组的最大和

2015-07-26 21:25 453 查看
题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组,求所有子数组的和的最大值。要求时间复杂度为O(n).

这个解法可以用动态规划来解。

其代码为:

package LinkList;

public class FindMaxSumofSubArrayMain {

public static int maxSubSum(int[] a) {
int maxSum = 0, thisSum = 0;
if (a == null || a.length <= 0)
return 0;
for (int i = 0; i < a.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, -2, 3, 10, -4, 7, 2, -5 };
System.out.println(maxSubSum(a));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: