【题目】
输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
【code】
解法一:暴力法
#include<iostream>
//#include<vector>
#include<stack>
#include<algorithm>
//#include<stack>
#include<queue>
#include<set>
using namespace std;
int findGreatestSumOfSubarray(vector<int>& nums)
{
int max = 0;
int size = nums.size();
for (int i = 0; i < size; i++)
{
int sum = 0;
for (int j = i; j < size; j++)
{
sum += nums[j];
if (sum>max)
{
max = sum;
}
}
}
return max;
}
int main()
{
vector<int> nums = { 1,-2,3,10,-4,7,2,-5 };
cout << findGreatestSumOfSubarray(nums) << endl;
return 0;
}
/****
***/
解法二:辅助空间O(N) + sort()
#include<iostream>
//#include<vector>
#include<stack>
#include<algorithm>
//#include<stack>
#include<queue>
#include<set>
using namespace std;
int findGreatestSumOfSubarray(vector<int>& nums)
{
int max = 0;
int size = nums.size();
vector<int> tmp(size+1);
tmp[0] = 0;
int sum = 0;
for (int i = 0; i < size; i++)
{
sum += nums[i];
tmp[i + 1] = sum;
}
sort(tmp.begin(), tmp.end());
max = tmp[size] - tmp[0];
return max;
}
int main()
{
vector<int> nums = { 1,-2,3,10,-4,7,2,-5 };
cout << findGreatestSumOfSubarray(nums) << endl;
return 0;
}
/****
***/
解法三:动态规划
#include<iostream>
//#include<vector>
#include<stack>
#include<algorithm>
//#include<stack>
#include<queue>
#include<set>
using namespace std;
int findGreatestSumOfSubarray(vector<int>& nums)
{
int max = 0;
int size = nums.size();
int sum = 0;
for (int i = 0; i < size; i++)
{
if (sum<=0)
{
sum = nums[i];
}
else
{
sum += nums[i];
}
if (sum>max)
{
max = sum;
}
}
return max;
}
int main()
{
vector<int> nums = { 1,-2,3,10,-4,7,2,-5 };
cout << findGreatestSumOfSubarray(nums) << endl;
return 0;
}
/****
***/