zoukankan      html  css  js  c++  java
  • java-最大连续子数组和(最大字段和)

    1.题目要求

      给定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。

    2.代码实现

    public class MaxArray {
    	
    	public static void main(String[] args){
    		int arr[] = {-2,11,-4,13,-5,-5,-2};
    		int result = maxSubArray(arr);
    	    System.out.println("最大子段和为:"+result);
    	}
    	
    	public static int maxSubArray(int[] arr){
    		int sum = 0;
    		int maxsum = 0;
    		for(int i = 0; i < arr.length; i ++){
    			if(sum <= 0){
    				sum = arr[i];
    			}else{
    				sum += arr[i];
    			}
    			if(sum > maxsum){
    				maxsum = sum;
    			}
    		}
    		return maxsum;
    	}
    }
    

    代码已上传到 GitHub

    3单元测试选择:条件组合覆盖

    3.1覆盖标准

      使得每个判定中条件的各种可能组合都至少出现一次。

    3.2条件选择的程序流程图如下

    条件组合 执行路径
    sum<=0,sum>=maxsum acdf
    sum>0,sum>=maxsum abdf
    sum>0,sum< maxsum abdef
    sum<=0,sum< maxsum acdef

    测试数据只需要一组[5,2,-8,3]即可实现上述四种执行路径

    3.3测试代码

    import static org.junit.Assert.*;
    import org.junit.Test;
    
    public class MaxArrayTest {
    
    	@Test
    	public void testMaxSubArray() {
    		int[]  arr={5,2,-8,3};
    		assertEquals(7,MaxArray.maxSubArray(arr));
    	}
    }
    

    3.4测试结果

  • 相关阅读:
    [leetcode]_Search Insert Position
    [leetcode]_Merge Two Sorted Lists
    [leetcode]_Valid Parentheses
    喧闹中坚守底线-徘徊的行走在不知道路在何方的大地上。
    [leetcode]_Longest Common Prefix
    [leetcode]_Remove Nth Node From End of List
    [leetcode]_Roman to Integer
    [leetcode]_Palindrome Number
    策略模式(Strategy)
    面向对象
  • 原文地址:https://www.cnblogs.com/zixinyang/p/10705962.html
Copyright © 2011-2022 走看看