Middle-题目18:53. Maximum Subarray

原创 2016年05月31日 15:41:53

题目原文:
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.
题目大意:
给一个数组,求和最大的连续的子数组。
题目分析:
用dp[n]代表结尾为n的连续子数组的和最大值,则有如下转移方程:

dp[n] = dp[n-1]+a[n]   dp[n-1]>0
        a[n]           others

即如果以n-1为结尾的子数组和是>0的,则前n-1项对n为结尾是“有贡献”的,那么以n为结尾的子列和就带上前面那个数组。否则从第n项开始。最后返回dp[n]里面最大值即可。因为dp[n]只跟dp[n-1]有关,故维护dp[n-1]一个变量就可以了。
源码:(language:java)

public class Solution {
    public int maxSubArray(int[] nums) {
        int maxsum = -9999999;
        int sumk = 0;
        for(int num : nums) {
            sumk = (sumk + num > num) ? sumk + num : num;
            maxsum = (maxsum > sumk) ? maxsum : sumk;
        }
        return maxsum;
    }
}

成绩:
1ms,beats 69.81%,众数2ms,55.83%
Cmershen的碎碎念:
这是DP问题里面最经典的题之一,此算法叫做Kadane算法。这个优美的算法由Carnegie Mellon University的统计学家Jay Kadane于1984年给出。

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

LeetCode(53) Maximum Subarray

题目Find the contiguous subarray within an array (containing at least one number) which has the larges...

leetcode刷题之旅——53. Maximum Subarray

本周写的第二道分治算法的题目,因为上次选择的是一道easy的题目,为了提升自己,这次选择了一道middle难度的题目。虽然这道题目是middle的,但是我还是想了很长时间。其实这道题目可以用动态规划直...

53. Maximum Subarray

Quesition Find the contiguous subarray within an array (containing at least one number) which has ...

LeetCode 53. Maximum Subarray(dynamic programming)

题目链接:https://leetcode.com/problems/maximum-subarray/ 题目描述: Find the contiguous subarray within an ...

[LeetCode]53.Maximum Subarray

【题目】 Find the contiguous subarray within an array (containing at least one number) which has the l...

53.Maximum Subarray | LeetCode 解题思路

本题来源于LeetCode devide and conquer题库,难度easy。

Leetcode53 Maximum Subarray

Maximum Subarray Find the contiguous subarray within an array (containing at least one number) whi...

53. Maximum Subarray

题目: Find the contiguous subarray within an array (containing at least one number) which has the...

Leetcode题解 - 53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest ...

[LeetCode] 53. Maximum Subarray

[LeetCode] 53. Maximum Subarray(Medium) 分治算法实践
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)