码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode53 Maximum Subarray

时间:2016-09-10 00:04:46      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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. (Medium)

分析:

遍历一遍,维护一个当前最大值temp,如果temp < 0,则temp = nums[i](前面的元素和更小,不要加进去), 否则 temp += nums[i];

然后每个temp更新result.

代码:

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         if (nums.size() == 0) {
 5             return -1;
 6         }
 7         int temp = nums[0], result = nums[0];
 8         for (int i = 1; i < nums.size(); ++i) {
 9             if (temp < 0) {
10                 temp = nums[i];
11                 result = max(temp, result);
12             }
13             else {
14                 temp = nums[i] + temp;
15                 result = max(temp, result);
16             }
17         }
18         return result;
19     }
20 };

题目还有分治和动归的算法,明天再说...

 

LeetCode53 Maximum Subarray

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5858203.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!