53. Maximum Subarray

来源:互联网 发布:淘宝免费买东西的技巧 编辑:程序博客网 时间:2024/06/04 01:22

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.

这是一道动态规划问题,第一遍写的时候建立了一个二维数组,记录nums[i]到nums[j]的和,从而找出最大值,但是会runtime error。
其实这道题只要找对sub problem,就不需要开二维数组,具体思路可参考https://discuss.leetcode.com/topic/6413/dp-solution-some-thoughts

class Solution {public:    int maxSubArray(vector<int>& nums) {        int n = nums.size();        int subAns[n];        subAns[0] = nums[0];        int max = subAns[0];        for (int i = 1; i < n; i++) {            subAns[i] = nums[i] + (subAns[i-1] > 0 ? subAns[i-1] : 0);            if (subAns[i] > max) {                max = subAns[i];            }        }        return max;    }};
原创粉丝点击