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

19.2.8 [LeetCode 53] Maximum Subarray

时间:2019-02-08 18:36:30      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:src   code   while   turn   style   solution   coding   another   ide   

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.

题意

求连续子集的最大和

题解

其实我觉得这题挺难的|||

首先是O(n)解法

技术图片
 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int e = 1, n = nums.size(), ans = nums[0], now = nums[0];
 5         while (e < n) {
 6             now = max(now + nums[e], nums[e]);
 7             ans = max(now, ans);
 8             e++;
 9         }
10         return ans;
11     }
12 };
View Code

然后是分治算法

技术图片
 1 class Solution {
 2 public:
 3     int maxSubRange(vector<int>&nums, int x, int y) {
 4         if (x == y)return nums[x];
 5         int mid = (x + y) / 2;
 6         int lmax = maxSubRange(nums, x, mid), rmax = maxSubRange(nums, mid + 1, y);
 7         int tmp = 0, mmax = 0;
 8         for (int i = mid - 1; i >= x; i--) {
 9             tmp += nums[i];
10             mmax = max(tmp, mmax);
11         }
12         tmp = mmax;
13         for (int i = mid; i <= y; i++) {
14             tmp += nums[i];
15             mmax = max(tmp, mmax);
16         }
17         return max(mmax, max(lmax, rmax));
18     }
19     int maxSubArray(vector<int>& nums) {
20         int e = 1, n = nums.size(), ans = nums[0], now = nums[0];
21         while (e < n) {
22             now = max(now + nums[e], nums[e]);
23             ans = max(now, ans);
24             e++;
25         }
26         return ans;
27     }
28 };
View Code

19.2.8 [LeetCode 53] Maximum Subarray

标签:src   code   while   turn   style   solution   coding   another   ide   

原文地址:https://www.cnblogs.com/yalphait/p/10356399.html

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