动态规划:最大字段和问题

import java.util.Scanner;

/*
 * 最大子段和问题,-2 11 -4 13 -5 -2中最大的子段和
 */
public class MaxSum {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int[] a=new int[n];
        boolean[] flag=new boolean[n];
        for (int i = 0; i < n; i++) {
            a[i]=scanner.nextInt();
            flag[i]=false;
        }
        int sum=0,max=0;
        for (int i = 0; i < a.length; i++) {
            sum+=a[i];
            if (sum>max) {
                max=sum;
                flag[i]=true;
            }
            else if (sum<0) {
                sum=0;
            }
        }
        System.out.println(max);
        int i=-1,j=flag.length;
        while (true){
            while (!flag[++i]);
            while (!flag[--j]);
            System.out.println(i+1+" "+j+1);
            break;
        }
    }
}

你可能感兴趣的:(算法)