假定给定的一组数为:-2,-4,-7,-20,1,1,1,1,-10,1,1,1,5,-10,10,10,10,-25,10,10,10,10,10,10,-300
算法要求:在给定的数组中找出某个连续子串,该子串的值是最大的,并且输出该子串和最大值。
代码如下:
public class Search {
static int max=0;
static int max1=0;
static int [] n = {-2,-4,-7,-20,1,1,1,1,-10,1,1,1,5,-10,10,10,10,-25,10,10,10,10,10,10,-300};
static String tempStr = "";
static String maxStr = "";
static int temp;
static String Find() {
for(int i = 0;i <25; i++) {
temp += n[i];
tempStr += n[i]+",";
if(temp >= max) {
maxStr = tempStr;
}
if(temp < 0) {
temp = 0;
tempStr = "";
}
}
System.out.println(maxStr);
return maxStr;
}
static int findNum() {
for(int i = 0;i<n.length;i++) {
temp += n[i];
if(temp > max) {
max = temp;
}
if(temp < 0) {
temp = 0;
}
}
return max;
}
public static void main(String[] args) {
Find();
System.out.println(findNum());
}
代码解析:对于给定的一串数值,可以将它们放在一个数组中。temp为滑动窗口,从数组首部遍历到尾部,当n[i]<0时,temp跳过到下一个数组元素,知道出现第一个数组元素不为负数的情况,然后temp连加后面的数组元素直到temp<0,将temp连加的最大值不断更新保存在最大值变量max中,知道temp遍历完整个数组,返回最大值max。再求最大连续子串时,道理类似,定义两个变量用于保存当前数组元素和最大值时的数组元素,每当temp变大,max更新时,将当前数组元素赋值给maxstr,最后输出maxStr。