LeetCode OJ-53.Maximum Subarray(最大连续子数组和)

LeetCode OJ-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.

click to show more practice.

Subscribe to see which companies asked this question

题目理解

​ 使用动态规划可以很好地解决问题,状态方程也不难写,设dp[i]为,到i位置为止,最大的连续子数组和。状态方程可以写作:dp[i] = MAX(dp[i - 1] + nums[i], nums[i])。时间复杂度O(n),空间复杂度,需要一个dp数组,需要动态申请,O(n)。

Code

int max_sub_sum(vector<int> &nums)
{
    int res = nums[0];
    int *dp = new int[nums.size()];
    dp[0] = nums[0];
    int i;
    for (i = 1; i < nums.size(); ++i) {
        dp[i] = MAX(dp[i - 1] + nums[i], nums[i]);
    }

    for (i = 0; i < nums.size(); ++i) {
        res = MAX(res, dp[i]);
    }
    delete []dp;
    return res;
}

你可能感兴趣的:(OJ-DP,leetcode,ACM,OJ,DP,最大连续子数组和)