网站建站的类型北京网站优化对策
2023.7.28
要求找最大和的 连续子数组, 我的思路是用一个temp记录局部最优值,用ans记录全局最优值。 然后在每次for循环进行一个判断:当前遍历元素+temp值 是否大于当前遍历元素的值,如果大于,说明temp值是帮了正忙的,所以让temp += 当前元素值;如果小于,说明temp是帮了倒忙的,此时让temp = 当前元素值。 再更新全局最优值。
下面看代码:
class Solution {
public:int maxSubArray(vector<int>& nums) {int ans = nums[0];int temp = nums[0];for(int i=1; i<nums.size(); i++){if(temp + nums[i] > nums[i]) temp += nums[i];else temp = nums[i];if(temp > ans) ans = temp;}return ans;}
};