题目
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.
题意
从数组中求出连续数的和的最大值。
思路
1. 暴力解法(时间复杂度为O(n2) 超时了)
C++语言
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int max=-pow(2,31),temp=0;
for(int i=0; i<nums.size(); i++)
{
temp = 0;
for(int j=i; j<nums.size(); j++)
{
temp+=nums[j];
if(max<temp)
max = temp;
}
}
return max;
}
};
2. 优化解法 (时间复杂度为0(n))
设temp为数组遍历的累加值,当前累加值大于大于max_sum时就将temp的值记录给max_sum,一旦当前的累加值小于0时,就将temp重置为0,接着累加。
C++语言
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int max=-pow(2,31),temp=0;
for(int i=0; i<nums.size(); i++)
{
temp += nums[i];
if(temp > max)
max = temp;
if(temp< 0)
temp = 0;
}
return max;
}
};
Python语言
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max = -(1<<31)
temp = 0
for num in nums:
temp = temp + num
if temp > max:
max = temp
if temp < 0:
temp = 0
return max