Find the contiguous subarray within an array (containing at least one number) which has the largest sum.spa
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
.code
分析:這道題是到很經典的題,關鍵點是要明白sum爲負數的連續subarray對可能的最大值沒有幫助(除該連續subarray的sum爲largest sum外)。因此很簡單的,若是sum小於0,咱們便置sum爲0。代碼以下:blog
class Solution { public: int maxSubArray(int A[], int n) { int result = INT_MIN; int sum = 0; for(int i = 0; i < n; i++){ sum += A[i]; result = max(result, sum); if(sum < 0) sum = 0; } return result; } };