返回一个整数数组中最大子数组的和1

一、要求

输入一个整形数组,数组里有正数也有负数。

数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

求所有子数组的和的最大值。要求时间复杂度为O(n)

二、思路:

1、从第一个元素开始循环,在嵌套另一个循环,从每个元素开始,依次加上后边的元素

2、当和大于最大值时,把和赋值给最大值,并记录此时的首元素的下标和尾元素的下标

三、实验代码:

package demo3;
public class Route {
    public static void main(String[] args) {
        int a[] = { 3, 8, -2, -5, -2 };
        int start = 0, end = 0;
        int maxnumber = a[0], s = a[0];
        for (int i = 0; i < a.length; i++) {
            s = a[i];
            if (s > maxnumber)
            {
                maxnumber = s;
                start = i;
                end = i;
            }
            for (int j = i + 1; j < a.length; j++)
            {
                s += a[j];
                if (s > maxnumber)
                {
                    maxnumber = s;
                    start = i;
                    end = j;
                }    
            }
        }
        System.out.print("该数组是:");
        for (int i = 0; i < a.length; i++)
        {
            System.out.print(a[i] + " ");
        }
        System.out.println();
        System.out.println("最大子数组的和是:" + maxnumber);
        System.out.print("最大子数组为:");
        for (int i = start; i <= end; i++)
        {
            System.out.print(a[i] + " ");
        }
    }
}

四、结果截图:

五、总结:

通过这次这个求所有子数组的和的最大值的要求,我发现我的逻辑思维还是没有跟不上,这道题主要在于怎么去想,然后才是实际下手编程,而且在编的过程中我们也要时刻想着这样写是为什么,下一步又改怎么写,只有这样,逻辑思维能力才能上去

原文地址:https://www.cnblogs.com/dmego/p/7015893.html