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
.
int maxSubArray(vector<int>& nums) { int sum=0, max_sum=INT_MIN; for(auto val:nums) { sum=max(val,val+sum); max_sum=max(sum,max_sum); } return max_sum; }
收获:
1. 最小值或者最大值的设置,最好使用 INT_MIN 或 INT_MAX;
2. 比较两个数的大小,最好使用max 或者 min;