53. Maximum Subarray
my program:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int result = nums[0];
int sum = 0;
for (int i = 0; i<nums.size(); ++i)
{
sum = 0;
for (int j = i; j<nums.size();++j)
{
sum += nums[j];
if (sum > result) result = sum;
}
}
return result;
}
};
Submission Result: Time Limit Exceeded
这个就是所谓的蛮力法吧…….%>_<%
时间复杂度是O(n2),当数据集越大,执行所需的时间就成平方数量级的增长,所以计算所需的时间超出了规定的时间,无法AC.
分治算法
首先将其分成两半A[l..m]和A[m+1..r],其中m=(l+r)/2,并分别求递归求出这两半的最大子串和
中间middle部分是两个循环,分别找出左边和右面(包含m点)的最大子串和.
最后取left
ightmiddle中最大值
程序如下:
class Solution {
public:
int solve(vector<int>& nums, int begin, int end)
{
if (begin == end) return nums[begin];
int mid = (begin+end) / 2;
int leftMax = solve(nums, begin, mid);
int rightMax = solve(nums, mid+1, end);
int midLeftMax = nums[mid];
int sumMidLeft = nums[mid];
for (int i = mid-1; i>=begin; --i)
{
sumMidLeft += nums[i];
midLeftMax = max(midLeftMax, sumMidLeft);
}
int midRightMax = nums[mid];
int sumMidRight = nums[mid];
for (int j = mid+1; j<=end; ++j)
{
sumMidRight += nums[j];
midRightMax = max(midRightMax, sumMidRight);
}
return max(max(leftMax, rightMax),midLeftMax+midRightMax-nums[mid]);
}
int maxSubArray(vector<int>& nums) {
return solve(nums, 0, nums.size()-1);
}
};
Simplest and fastest O(n) C++ solution:
Idea is very simple. Basically, keep adding each integer to the sequence until the sum drops below 0.
If sum is negative, then should reset the sequence.
class Solution {
public:
int maxSubArray(int A[], int n) {
int ans=A[0],i,j,sum=0;
for(i=0;i<n;i++){
sum+=A[i];
ans=max(sum,ans);
sum=max(sum,0);
}
return ans;
}
};
此算法的时间复杂度是O(n),当数据非常大的时候,比起时间复杂度是O(n2)的算法好的不是一点.