Middle-题目18:53. 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.
题目大意:
给一个数组,求和最大的连续的子数组。
题目分析:
用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 https://blog.csdn.net/cmershen/article/details/51546290
个人分类: Leetcode
上一篇Middle-题目17:116. Populating Next Right Pointers in Each Node
下一篇Middle-题目19:309. Best Time to Buy and Sell Stock with Cooldown
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭