【剑指offer】面试题 42. 连续子数组的最大和

面试题 42. 连续子数组的最大和

NowCoder

题目描述
输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。

示例:

输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

注意: 要求时间复杂度为 O(n)。

Java 实现

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if (array == null || array.length == 0) {
            return 0;
        }
        int result = Integer.MIN_VALUE;
        int max = 0;
        for (int num : array) {
            max = Math.max(max + num, num);
            result = Math.max(result, max);
            System.out.println(result);
        }
        return result;
    }
}

相似题目

猜你喜欢

转载自www.cnblogs.com/hglibin/p/10908860.html