1. 題目
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.
2. 思路
遍歷查詢每段的最大sum。如果當前段的sum已經小於0,則重新開啟一段。
特別注意的是:陣列裡可能全部是負數,因此,負數的值也是要進入max比較的。sum起點要選擇最小值。
3. 程式碼
class Solution {
public:
// 遍歷找到當前的最大sum點, 噹噹前sum小於0後,重置
int maxSubArray(vector<int>& nums) {
int sum = numeric_limits<int>::min();
int c_sum = 0;
for (int i = 0; i < nums.size(); i++) {
if (c_sum < 0) {
c_sum = 0;
}
c_sum += nums[i];
if (c_sum > sum) {
sum = c_sum;
}
}
return sum;
}
};