【LeetCode】53. Maximum Subarray (2 solutions)
Maximum Subarray
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
.
解法一:
如果当前子串和小于等于0,则归零重新开始累加。记录最大子串和。
注意:ret需要初始化为INT_MIN(以防所有都为负)。
因此需要定义为long long类型。以防INT_MIN加上一个负数溢出。
class Solution { public: int maxSubArray(int A[], int n) { long long ret = INT_MIN; long long cur = INT_MIN; for(int i = 0; i < n; i ++) { if(cur + A[i] > A[i]) cur += A[i]; else cur = A[i]; ret = max(ret, cur); } return ret; } };
或者初始化为第一个值
class Solution { public: int maxSubArray(vector<int>& nums) { int ret = nums[0]; int cur = nums[0]; for(int i = 1; i < nums.size(); i ++) { cur = max(nums[i], cur+nums[i]); ret = max(ret, cur); } return ret; } };
解法二:分治法。将数组分成两段A1,A2之后,就分解成为子问题了:
1、最大子串在A1中;
2、最大子串在A2中;
3、最大子串是A1后缀+A2前缀。
class Solution { public: int maxSubArray(int A[], int n) { if(n == 1) return A[0]; else { int mid = n/2; //divide into [0~mid-1], [mid~n-1] int ret1 = maxSubArray(A, mid); int ret2 = maxSubArray(A+mid, n-mid); int left = mid-1; int ret3_1 = A[mid-1]; int temp = A[mid-1]; left --; while(left >= 0) { temp += A[left]; ret3_1 = max(ret3_1, temp); left --; } int right = mid; int ret3_2 = A[mid]; temp = A[mid]; right ++; while(right < n) { temp += A[right]; ret3_2 = max(ret3_2, temp); right ++; } return max(max(ret1, ret2), ret3_1+ret3_2); } } };