代码:
package com;
import java.util.*;
public class LargestSubsegmentSum2
{
public static void main(String[] args)
{
/**
*从键盘输入所要求的序列的长度n
*/
Scanner in=new Scanner(System.in);
System.out.println("输入你要求的序列的长度:");
int n=in.nextInt();
/**
*从键盘输入所要求的序列,存储在a[n]中
*/
int[] a=new int[n];
System.out.println("现在请依次输入这个序列包含的元素(整数):");
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
/**
*调用函数MaxSum()求解出结果
*/
int maxSum=MaxSum(a,0,n);
/**
*打印输出结果和程序运行所用时间
*/
System.out.println("最大子段和是:"+maxSum);
}
/**
*设计求解最大子段和的函数MaxSum()
*/
public static int MaxSum(int[] a,int left,int right)
{
int maxSum=0;
if(left==right)
{
if(a[0]>0)
maxSum=a[0];
}
else
{
int center=(left+right)/2;
int maxSum1=MaxSum(a,left,center);
int maxSum2=MaxSum(a,center+1,right);
int s1=0;
int lefts=0;
for(int i=center;i>=left;i--)
{
lefts+=a[i];
if(lefts>s1)
s1=lefts;
}
int s2=0;
int rights=0;
for(int j=center+1;j<right;j++)
{
rights+=a[j];
if(rights>s2)
s2=rights;
}
maxSum=s1+s2;
if(maxSum<maxSum1)
maxSum=maxSum1;
if(maxSum<maxSum2)
maxSum=maxSum2;
}
return maxSum;
}
}
运行结果:
输入你要求的序列的长度:
5
现在请依次输入这个序列包含的元素(整数):
5 -4 4 3 -2
最大子段和是:8
package kaoshi;
//动态规划算法
import java.util.*;
public class LargestSubsegmentSum3 {
public static void main(String[] args) {
/**
* 从键盘输入所要求的序列的长度n
*/
Scanner in = new Scanner(System.in);
System.out
.println("Please enter the length of segment you want to make(输入你要求的序列的长度):");
int n = in.nextInt();
/**
* 从键盘输入所要求的序列,存储在a[n]中
*/
int[] a = new int[n];
System.out
.println("Now,please enter the elements of the segment you want(现在请依次输入这个序列包含的元素(整数)):");
int i;
for (i = 0; i < n; i++) {
a[i] = in.nextInt();
}
/**
* 求解最大子段和存在maxSum中
*/
double startTime = System.currentTimeMillis();// starttime
int maxSum = 0;
int[] b = new int[n];
b[0] = 0;
for (int j = 1; j < n; j++) {
if (b[j - 1] > 0)
b[j] = b[j - 1] + a[j];
else {
b[j] = a[j];
i = j;
}
}
for (int j = 0; j < n; j++) {
if (b[j] > maxSum)
maxSum = b[j];
}
double endTime = System.currentTimeMillis();// endtime
/**
* 打印输出结果和程序运行所用时间
*/
System.out.println("The largest sub-segment sum is(最大子段和是):" + maxSum);
System.out.println("Basic Statements take(基本语句用时) "
+ (endTime - startTime) + " milliseconds!");
}
}