classSolution { public: intmaxSubArray(vector<int>& nums){ int SizeofNums = nums.size(); if(SizeofNums == 1) { return nums[0]; } int sums[SizeofNums]; sums[0] = nums[0]; for(int i=1; i<SizeofNums; i++) { // sums[i]: The largest sum of subarray ending with the i-th element sums[i] = sums[i-1]<0 ? nums[i] : sums[i-1]+nums[i]; } // The largest sum of the whole array int largestSum = sums[0]; for(int i=1; i<SizeofNums; i++) { if(largestSum < sums[i]) { largestSum = sums[i]; } } return largestSum; } };
为了得到 largestSum 对应的子序列,我们可以通过变量 startIdx 记录以第 j 个元素结尾(endIdx)的最大子段和对应子序列的起始位置,$nums[startIdx, …, endIdx]$ 即为对应的子序列;另外,考虑到当前状态只与前一个状态有关,所以可以使用变量代替数组,节省内存,同时,避免获取The largest sum of the whole array 时的重复循环。
classSolution { public: intmaxSubArray(vector<int>& nums){ int SizeofNums = nums.size(); if(SizeofNums == 1) { return nums[0]; } // largest sum for the subarray ending with current element int curSum = nums[0]; // largest sum of subarray for the whole array int largestSum = curSum; // subarray[startIdx, endIdx] with largest sum for the whole array int startIdx = 0, endIdx = 0; for(int i=1; i<SizeofNums; i++) { if(curSum < 0) { curSum = nums[i]; startIdx = i; } else { curSum = curSum + nums[i]; } if(curSum > largestSum) { largestSum = curSum; endIdx = i; } } return largestSum; } };