leetcode 53. Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 额,我现在分不清这种方法是dp还是什么;

用temp记录连续子集的和, 如果连续子集比当前元素小,就把temp设置为当前值, max记录连续子集 的最大和。 感觉是dp

注意点:maxx的初始值应该为-2147483647,即整形的最小数

 1 class Solution {
 2 public:
 3     int maxx=-2147483647, temp=0;
 4     int maxSubArray(vector<int>& nums) {
 5         for(int i=0; i<nums.size(); i++){
 6             temp = max(nums[i], temp+nums[i]);
 7             maxx = max(maxx, temp); 
 8         }
 9         return maxx;
10     }
11 };
有疑惑或者更好的解决方法的朋友,可以联系我,大家一起探讨。qq:1546431565
原文地址:https://www.cnblogs.com/mr-stn/p/9218815.html