Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
思路一:暴力搜索,最笨的方法
代码如下:
class Solution {public: int maxSubArray(vector<int>& nums) { int size = nums.size(); int max = 0x80000000,sum=0; for(int i=0;i<size;i++) { sum = 0; for(int j=i;j<size;j++) { sum += nums[j]; if(sum > max) max = sum; } } return max; }};已哭晕在厕所,想想怎么优化
思路二:寻找特性,进行减枝操作。当sum小于0时,其加上后面的数只会使得sum更小,所以此时sum与max进行对比,然后就sum置为0,从下一个位置开始计算
代码如下:
class Solution {public: int maxSubArray(vector<int>& nums) { int size = nums.size(); int max = 0x80000000,sum=0; for(int i=0;i<size;i++) { sum += nums[i]; if(sum > max) max = sum; if(sum < 0) sum = 0; } return max; }};
新闻热点
疑难解答