Maximum Subarray 动态规划 最大连续子序列和

来源:互联网 发布:mac怎么打开mobi文件 编辑:程序博客网 时间:2024/05/16 01:49

转载自:http://www.acmerblog.com/leetcode-solution-maximum-subarray-6334.html

题目:https://leetcode.com/problems/maximum-subarray/description/

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

标签: Divide and Conquer Array Dynamic Programming
分析

最大连续子序列和,非常经典的题。

当我们从头到尾遍历这个数组的时候,对于数组里的一个整数,它有几种选择呢?它只有两种选择: 1、加入之前的SubArray;2. 自己另起一个SubArray。那什么时候会出现这两种情况呢?

如果之前SubArray的总体和大于0的话,我们认为其对后续结果是有贡献的。这种情况下我们选择加入之前的SubArray

如果之前SubArray的总体和为0或者小于0的话,我们认为其对后续结果是没有贡献,甚至是有害的(小于0时)。这种情况下我们选择以这个数字开始,另起一个SubArray。

设状态为{f[j]},表示以{S[j]}结尾的最大连续子序列和,则状态转移方程如下:

f[j]target==max{f[j1]+S[j],S[j]},  1jnmax{f[j]},  1jn

解释如下:

\item 情况一,S[j]不独立,与前面的某些数组成一个连续子序列,则最大连续子序列和为$f[j-1]+S[j]$。
\item 情况二,S[j]独立划分成为一段,即连续子序列仅包含一个数S[j],则最大连续子序列和为$S[j]$。

其他思路:

\item 思路2:直接在i到j之间暴力枚举,复杂度是$O(n^3)$
\item 思路3:处理后枚举,连续子序列的和等于两个前缀和之差,复杂度$O(n^2)$。
\item 思路4:分治法,把序列分为两段,分别求最大连续子序列和,然后归并,复杂度$O(n\log n)$
\item 思路5:把思路2$O(n^2)$的代码稍作处理,得到$O(n)$的算法
\item 思路6:当成M=1的最大M子段和

 public int maxSubArray(int[] nums) {        int res = Integer.MIN_VALUE, curSum = 0;        for (int num : nums) {            curSum = Math.max(curSum + num, num);            res = Math.max(res, curSum);        }        return res;    }


原创粉丝点击