TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a+a[i+1]+…+a[j]的子段和的最大值。
当所给的整数均为负数时定义子段和为0,依此定义,所求的最大值为:
Max{0,a+a[i+1]+…+a[j]},1<=i<=j<=n
例如,当(a1,a2,a3,a4,a4,a6)=(-2,11,-4,13,-5,-2)时,最大子段和为20.
- import java.util.Scanner;
- public class MaxSequence{
-
- public static int[] findMaxSequence(int n, int[] seq){
- /* seq为传入的整型数组,n为数组长度, start, end分别用来返回所找到的最长子串的起始下标和截止下标 */
- int maxsofar = 0;
- int maxendinghere = 0;
- int starthere = 0;
- int start=0;
- int end= 0;
- for ( int i = 0; i < n; i++ )
- {
- if ( maxendinghere + seq[i] >= 0 )
- maxendinghere = maxendinghere + seq[i];
- else
- {
- maxendinghere = 0;
- starthere = i+1;
- }
- if ( maxendinghere > maxsofar ||((maxendinghere == maxsofar) && (end - start) < (i - starthere)))
- {
- maxsofar = maxendinghere;
- start = starthere;
- end = i;
- }
- }
- return new int[]{start,end,maxsofar};
- }
-
- public static void main(String[] args) {
- /**
- *从键盘输入所要求的序列的长度n
- */
- Scanner in=new Scanner(System.in);
- int n=in.nextInt();
-
- /**
- *从键盘输入所要求的数组,存储在a[n]中
- */
- int[] a=new int[n];
- for(int i=0;i< n;i++) {
- a[i]=in.nextInt();
- }
- int result[]=findMaxSequence(n,a);
- System.out.println("最大子段和是:"+result[2]);
- System.out.println("最大子段和构成:");
- for(int i=result[0];i<=result[1];i++)
- System.out.print(a[i]+" ");
- }
- }
-
- C: est>java MaxSequence
- 15
- 1 2 -1 1 3 2 -2 3 -1 5 -7 3 2 -2 -1
- 最大子段和是:13
- 最大子段和构成:
- 1 2 -1 1 3 2 -2 3 -1 5
- C: est>java MaxSequence
- 6
- -2 11 -4 13 -5 -2
- 最大子段和是:20
- 最大子段和构成:
- 11 -4 13
复制代码
源码下载:http://file.javaxxz.com/2014/12/6/000710343.zip |
|