软件工程(2019)第三次个人作业

  • 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
    例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。

二.源代码

import java.util.Scanner;
public class ziduanhe {
	
	public static void main(String[] args) {
		   int[] a=new int[100];
		   int i=0;
		   int count=0;
		   Scanner sc = new Scanner(System.in);  
		   count=sc.nextInt();
		   for(i=0; i<count; i++)
		   {
		       a[i]=sc.nextInt();
		   }
		   System.out.println(max(count,a));
	}
	public static int max(int count,int [] a) {
		int[] b=new int[100];
		int max,i;
		   b[0]=a[0];
		   max=b[0];
		   for(i=1; i<count; i++)
		   {
		       if(b[i-1]>0)
		       {
		           b[i]=b[i-1]+a[i];
		       }
		       else
		       {
		           b[i]=a[i];
		       }
		        if(b[i]>max) 
		        {
		           max=b[i];
		        }
		   }
		   if(max<0)
			   max=0;
		   return max;
	}
	
}

Github代码链接

三.判断/条件覆盖流程图


四.测试样例

import static org.junit.Assert.*;

import org.junit.Test;

import my1.ziduanhe;

public class ziduanheTest {

	@Test
	public void Testmax1() {
		new ziduanhe();
		assertEquals(0,ziduanhe.max(0,new int [] {0}));
	}
	@Test
	public void Testmax2() {
		new ziduanhe();
		assertEquals(0,ziduanhe.max(6,new int [] {-1,-2,-3,-4,-5,-6}));
	}
	@Test
	public void Testmax3() {
		new ziduanhe();
		assertEquals(20,ziduanhe.max(6,new int [] {-2,11,-4,13,-5,-2}));
	}
}

五.测试结果

原文地址:https://www.cnblogs.com/-yanghao/p/10715872.html