53 Maximum Subarray

xiaoxiao2021-02-27  544

class Solution { public: int maxSubArray(vector<int>& nums) { int length = nums.size(); int sum = 0 ; sum = nums[length-1]; int maxsum = sum ; //从后向前,因为连续的子序列是从前向后不断增加,而从后向前是不断减小的,只要加上当前的值小于了目前的还和,那就更新当前和为,当前元素的值。 for(int i = length - 2 ; i>=0 ; i-- ){ sum = max(nums[i] , sum + nums[i]); maxsum = max(sum,maxsum); } return maxsum; } };
转载请注明原文地址: https://www.6miu.com/read-3496.html

最新回复(0)