这个帖子是针对第三周做的53题的改进,应用动态规划使得时间复杂度缩小到O(n)。
思路:搬运自leetcode:
So I change the format of the sub problem into something like: maxSubArray(int A[], int i)
, which means the maxSubArray for A[0:i ] which must has A[i] as the end element. Note that now the sub problem's format is less flexible and less powerful than the previous one because there's a limitation that A[i] should be contained in that sequence and we have to keep track of each solution of the sub problem to update the global optimal value. However, now the connect between the sub problem & the original one becomes clearer:
通过这一子问题的分解使得原问题的答案就变成了所有maxSubArray中的最大值,同时注意到下一个maxSubArray的计算方法是temp=temp>0?temp+nums[i]:nums[i];非常精妙的思路,主要问题简化在于maxSubArray一定包括该数组范围内最后一个。代码如下
int maxSubArray(vector<int>& nums) {
int size=nums.size();
int temp=nums[0];
int Max=temp;
for(int i=1;i<size;i++)
{
temp=temp>0?temp+nums[i]:nums[i];
Max=max(Max,temp);
}
return Max;
}
总结:依旧是牢牢记住动态规划的步骤:寻找子问题最优解,合理优化局部结构。