码迷,mamicode.com
首页 > 编程语言 > 详细

(C++練習) 53. Maximum Subarray

时间:2019-02-23 01:11:32      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:least   divide   out   you   ast   another   pre   VID   col   

題目 : 

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.

大意 : 

給一個整數陣列, 找出陣列內最大的總和,必須是鄰近的數加總。

解法1:

 1 #define MAX(a,b) (a > b ? a : b)
 2 
 3 class Solution {
 4 public:
 5     int maxSubArray(vector<int>& nums) {
 6         int len = nums.size();
 7         int sum = 0, ans = nums[0];
 8         for (int i = 0; i < len; i++){
 9             sum += nums[i];
10             ans = MAX(sum, ans);
11             sum = MAX(sum, 0);
12         }
13         return ans;
14     }
15 };

 解法2:

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

 

(C++練習) 53. Maximum Subarray

标签:least   divide   out   you   ast   another   pre   VID   col   

原文地址:https://www.cnblogs.com/ollie-lin/p/10421361.html

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