题目:
输入一个整形数组,数组里有正数也有负数 ,数组中连续的一个或多个整数组组成一个子数组,每个数组都有一个和。求所有子数组的和的最大值
例如: 输入的数组为 1 -2 3 10 -4 7 2 -5 , 和最大的子数组为 3 10 -4 7 2 ,因此输出为该子数组的和 18
想法:从第一个(值给b )开始每一个和后面的相加,如果 b< 0 ,把之前的和给 sum b 从新开始加 如果 >sum b 的值给 sum 输出子数组的时候:将子数放入一个数组中,如果 b < 0 数组清零 输出的时候 去掉最后面 <0 的数
代码:
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
LinkedList<Word> mylist = new LinkedList<Word>();
LinkedList<Lat> list = new LinkedList<Lat>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try{
String s = reader.readLine();
String[] nums = s.split("//s+"); //匹配
for(String num : nums)
{
int a = Integer.parseInt(num) ;//转化为int型的
Word word = new Word(a);
mylist.add(word);
}
}catch(Exception e){}
int b = 0;
int sum = 0 ;
for(int i = 0 ; i < mylist.size(); i++)
{
if(b <= 0)
{
list.clear(); //清空链
b = mylist.get(i).getWord();
Lat lat = new Lat(mylist.get(i).getWord());//重新添加链表
list.add(lat);
}
else
{
b += mylist.get(i).getWord();
Lat lat = new Lat(mylist.get(i).getWord());
list.add(lat);
}
if(sum < b)
{
sum = b;
}
}
System.out.println("最大的和是:" + sum);
System.out.print("最大子组为: ");
while(list.size() != 0)
{
if(list.get(list.size() - 1 ).getLat() < 0) //如果最后的数 <0 , 去除最后的数
{
list.removeLast();
}
System.out.print(list.removeFirst().getLat() + " ");
}
}
}
class Word
{
private int body ;
public Word(int body)
{
this.body = body;
}
public int getWord()
{
return this.body;
}
}
class Lat
{
private int a ;
public Lat(int a)
{
this.a = a;
}
public int getLat()
{
return this.a ;
}
}