参考了网上的
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
.
思路在于要不要将现在的元素加入到之前的 array 中去。 非常好的一道题。
得到以每个元素结尾的最大子序列。 然后再用 O(n) 的时间去扫一遍。
C++
class Solution {
public:
int maxSubArray(int A[], int n) {
int f = 0, result = INT_MIN;
for (int i=0;i<n;i++){
f = max(f+A[i],A[i]);
result = max(result, f);
}
return result;
}
};
class Solution:
# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):
f,result = 0,float("-inf")
for i in A:
f = max(f+i,i)
result = max(result,f)
return result