[计蒜客] 最大子阵列(补充与扩展)

  • 问题描述:一个整数数组,找出所有连续子序列中和的最大的子序列,并输出起始坐标,终点坐标,最大和

  • 输入格式:

    第一行输入一个不超过1000的整数n。
    第二行输入n个整数A[i]。

  • 输出格式:

    第一行输出一个整数,表示起始坐标
    第二行输出一个整数,表示终点坐标
    第三行输出一个整数,表示最大和

  • 样例输入:
    3
    1 1 -2

  • 样例输出:
    0
    1
    2
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int[] input = new int[n];
            for (int i = 0; i < n; i++) {
                input[i] = in.nextInt();
            }
            int beginIndex = 0, endIndex = 0, sumMax = Integer.MIN_VALUE, sum = 0;
            for (int i = 0; i < n; i++) {
                if (sum > 0) {
                    sum += input[i];
                } else {
                    sum = input[i];
                    beginIndex = i;
                }
                if (sumMax < sum) {
                    sumMax = sum;
                    endIndex = i;
                }
            }
            if (beginIndex > endIndex) {//当数组全部是负数时
                beginIndex = endIndex;
            }
            System.out.println("最大子数组的和为:" + sumMax);
            System.out.println("最大子数组的索引:" + beginIndex + " " + endIndex);

        }
        in.close();
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值