动态规划--求最大连续子串之和

给定由n个整数(可能为负整数)组成的序列A1,A2,A3,…,An,求该序列的连续子段的和的最大值。
例如 {-4, 11,-2, 13,-7,-3,12} 的最大子段和为24

JAVA代码实现:

package com.example;

public class 最大连续子串之和 {
    /** * @param args */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a = {-4, 11, -2, 13, -7,- 3, 12} ;
        getMaxSumSeq(a);
    }

    private static void getMaxSumSeq(int[] a){
        int rmax = Integer.MIN_VALUE;
        int sum = Integer.MIN_VALUE;
        int start = -1;
        int end = -1;
        int temp = -1;
        for(int i = 0 ;i<a.length;i++)
        {
            if(sum>0)
            {
                sum+=a[i];
            }
            else
            {
                sum = a[i];
                temp = i;
            }
            if(sum>rmax)
            {
                start = temp;
                rmax= sum;
                end = i;
            }
        }
        for(int j = start;j<=end;j++)
        {
            System.out.print(a[j]+" ");
        }        
        System.out.println("\nsum:"+rmax);
    }
}

《动态规划--求最大连续子串之和》

点赞