题目:
给定一个数组,其中元素可正可负,求其中最大连续子序列的和。
解题思路
用temp记录累计值,num记录和最大
基于思想:对于一个数A,若是A的左边累计数非负,那么加上A能使得值不小于A,认为累计值对
整体和是有贡献的。如果前几项累计值负数,则认为有害于总和,temp记录当前值。
此时 若和大于num 则用num记录下来。
代码如下
public class Test {
public static void main(String[] args) {
int[] array = {2, -2, -3, -4, 1};
if (array.length == 0)
System.out.println(0);
else {
int temp = array[0];
int num = array[0];;
for (int i = 1; i < array.length; i++) {
if (temp >= 0)
temp += array[i];
else
temp = array[i];
if (temp > num)
num = temp;
}
System.out.println(num);
}
}
}
本文介绍了一种求解最大连续子序列和的算法,通过动态调整累计值,有效地找到数组中最大连续子序列的和。算法核心在于判断当前累计值是否对总和有益,若无益则重新开始累计。
1万+

被折叠的 条评论
为什么被折叠?



