[设计思路]
在之前(子数组求最大值)的基础之上,要使成环后的数组求取其最大子数组之和,需要确定遍历循环开始的位置和其结束的位置。
1.使用一个for循环,遍历至最后一个数。当某个数之前的子数组为负值(即子数组最大值要从当前数来计时),添加一个标记,作为下一个for循环停止的位置。
2.再使用一个for循环,遍历至标记所在处。
[程序代码]
import java.util.*; public class MaxsArray { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("请输入你要求子数组最大值的数组长度:"); int length = sc.nextInt(); int array[] = new int[length]; System.out.println("请输入你要求子数组最大值的数组的数:"); for(int i=0;i<length;i++) { array[i] = sc.nextInt(); } int max = array[0]; int tempmax = array[0]; int temp=0; for(int i=1;i<length;i++) { if(tempmax<0) { tempmax = array[i]; temp=i-1; } else { tempmax+=array[i]; } if(tempmax>max) { max = tempmax; } } for(int i=0;i<=temp;i++) { if(tempmax<0) { tempmax = array[i]; } else { tempmax+=array[i]; } if(tempmax>max) { max = tempmax; } } System.out.println("子数组的最大值为:"+max); } }
[结果截图]
[总结]
一个程序的设计思路对一个程序的实现远重于所花费在敲代码上的功夫,所以,在编写一个程序之前,一定要好好构建设计思路,只有思路清晰了才能快速的实现自己的程序。