首页 > 其他 > 详细

leetcode 53. Maximum Subarray

时间:2018-06-23 21:58:55      阅读:184      评论:0      收藏:0      [点我收藏+]

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 };

 

leetcode 53. Maximum Subarray

原文:https://www.cnblogs.com/mr-stn/p/9218815.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!