class Solution {
public:
int maxSubArray(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool isAllNeg = true;
int negMax = INT_MIN;
int j = 0;
while (j < n)
{
if (A[j] > 0)
{
isAllNeg = false;
break;
}
if (A[j] > negMax)
negMax = A[j];
++j;
}
if (isAllNeg) return negMax;
int maxSum = 0;
int curSum = 0;
int i = 0;
while (i < n)
{
curSum += A[i];
if (curSum > maxSum)
{
maxSum = curSum;
}
if (curSum < 0)
curSum = 0;
++i;
}
return maxSum;
}
};
[Leetcode] Maximum Subarray
最新推荐文章于 2021-10-21 15:55:14 发布