剑指offer第31题:连续子数组的最大和

来源:互联网 发布:知乎分享你刚编的经历 编辑:程序博客网 时间:2024/04/30 02:15

输入:一个整型数组,数组中一个或连续的多个整数构成一个子数组
输出:所有子数组的和的最大值,时间复杂度O(n)
思路:从起始位置开始计算,当前面的子数组和小于0时,重新设置起点;大于0时再加上接下来的元素,若所得和大于之前的最大值将之前的最大值置为所得和,若小于则之前的最大值不变

public class GreatestSumOfSubArray {//    剑指offer31,连续子数组的最大和    public int greatestSumOfSubArray(int[] array){        if(array == null || array.length == 0){            return 0;        }        int max = 0;        int tempMax = 0;        for(int i = 0; i < array.length; i ++){            if(max >= 0){                max += array[i];            }else {                max = array[i];            }            if(max > tempMax){                tempMax = max;            }        }        return tempMax;    }}
0 0
原创粉丝点击