(C++練習) 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.

大意 : 

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

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

猜你喜欢

转载自www.cnblogs.com/ollie-lin/p/10421361.html
今日推荐