连续子数组最大和

来源:https://leetcode.com/problems/maximum-subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

遍历(时间复杂度高)

  1. 若全负,取最大元素
  2. 否则比较以每个元素作为开头(或结尾)的所有连续子数组的和

Python

class Solution:
    def FindGreatestSumOfSubArray(self, array):
        if max(array) < 0:
            return max(array)
        max_sum = 0
        cur_sum = 0
        for i in range(len(array)):
            cur_sum = 0
            for j in range(i, len(array)):
                cur_sum += array[j]
                max_sum = max(cur_sum, max_sum)
        return max_sum

动态规划

遍历一次,计算以当前元素结尾的连续子数组和的最大值:

  1. 若以前一个元素结尾的连续子数组和的最大值为正,则,以当前元素结尾的连续子数组和的最大值 = 当前元素 + 以前一个元素结尾的连续子数组和的最大值
  2. 否则,以当前元素结尾的连续子数组和的最大值 = 当前元素

比较以当前元素结尾的连续子数组和的最大值与当前全局最大值

Python

class Solution:
    def FindGreatestSumOfSubArray(self, array):
        if not array:
            return 0
        max_sum, cur_sum = array[0], 0
        for item in array:
            if cur_sum <= 0:
                cur_sum = item
            else:
                cur_sum += item
            max_sum = max(max_sum, cur_sum)
        return max_sum

Java

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length <= 0) {
            return 0;
        }
        int maxSum = nums[0], curSum = nums[0];
        for(int i=1; i<nums.length; i++) {
            if(curSum < 0) {
                curSum = nums[i];
            } else {
                curSum += nums[i];
            }
            maxSum = curSum > maxSum ? curSum : maxSum;
        }
        return maxSum;
    }
}
posted @ 2017-09-04 09:03  HitAnyKey  阅读(244)  评论(0编辑  收藏  举报