个人作业—数组

package sz;

public class sz1 {
    public static void main(String[] args) {
        int[] a= {-1,-2,-4,-8,-4,-7,-1,-5};
        System.out.println(max(a));
    }
    public static int max(int[] array) {
        int n=array.length;
        int max=0;
        int maxsum=array[0];
        for(int i = 0;i < n;i++)
        {
            if (max <= 0) {
                max = array[i];
            }else {
                max += array[i];
            }
            
            if (maxsum < max) {
                maxsum = max;
            }
        }
        return maxsum;
}
}

以上是实验代码:如上

时间复杂度:O(n)

设计思路:连续数组有正有负,从首遍历 遇到负数将负数省略掉,从第一个正数开始累加 ,累加后有个判断是否小于0,若小于0,进行新的累加,最后返回最大值

实验截图

上面的方法是我能写出的时间复杂度为O(n)的最简方法。

猜你喜欢

转载自www.cnblogs.com/cuijunfeng/p/10506214.html