53. Maximum Subarray

来源:互联网 发布:医疗卫生软件竞争格局 编辑:程序博客网 时间:2024/05/03 16:55

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问题来看,到当前位置的最大和,如果它小于0,对后面没有任何帮助,不论后面一个数是正是负,所以可以拿当前位置的值重新开始累加。
http://www.acmerblog.com/leetcode-solution-maximum-subarray-6334.html

class Solution {public:    int maxSubArray(vector<int>& nums) {         int result = INT_MIN, f = 0;         for(int i = 0; i < nums.size(); i++)         {             f = f < 0? nums[i]:nums[i] + f;             result = max(result, f);         }         return result;    }};
0 0
原创粉丝点击