题目分析
这个题目是我在西安交通大学的夏令营的机式时遇到的,当时我用了两个for循环,用的最原始的办法,由于时间太长,所以得了A-
给定一个整数数组nums,找到一个具有最大和的连续子数组(子数组最少包含一个元素返回其最大和。
代码1
这里的代码是我看完LeeCode上的解说写的:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int p=0,a=nums[0];
for(const auto&x:nums){//对于数组中的每一个元素
p=max(p+x,x);
a=max(p,a);
}
return a;
}
};
这里我们用const auto& x:nums来读取nums中的每一个数组:
想要拷贝元素:for(auto x:range)
想要修改元素 : for(auto &&x:range)
想要只读元素:for(const auto& x:range)
题目来自LeeCode,此处还有更加快速的方法
题目的思想
我们假设f(i)是以第i个数字为结尾的序列的和的最大值:f(i)=max{f(i−1)+ai,ai}
时间复杂度为O(n),空间复杂度为O(1)。