美文网首页
53. Maximum Subarray

53. Maximum Subarray

作者: YellowLayne | 来源:发表于2017-06-16 13:58 被阅读0次

    1.描述

    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.

    2.分析

    简单的动态规划问题。

    3.代码

    int maxSubArray(int* nums, int numsSize) {
        if (NULL == nums) exit(0);
        if (1 == numsSize) return nums[0];
        int *dp = (int*)malloc(sizeof(int) * numsSize);
        if (NULL == dp) exit(0);
        
        int maxSum = dp[0]=nums[0];
        for (unsigned int i = 1; i < numsSize; ++i) {
            dp[i] = dp[i-1] > 0 ? dp[i-1] + nums[i] : nums[i];
            if (dp[i] > maxSum) maxSum = dp[i];
        }
        
        if (dp) {
            free(dp);
            dp = NULL;
        }
        return maxSum;
    }
    

    相关文章

      网友评论

          本文标题:53. Maximum Subarray

          本文链接:https://www.haomeiwen.com/subject/cxxmqxtx.html