LeetCode Maximum Subarray

题目:

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.

分析与解答:

这应该是算法导论上的原题,分治法当然也是可以的。但是存在O(n)时间的解法。

class Solution {
public:
    int maxSubArray(int A[], int n) {
        int index = 0,temp_sum = 0,max_sum = INT_MIN;
        while(index < n){
            temp_sum += A[index];
            if(temp_sum > max_sum){
                max_sum = temp_sum;
            }
            if(temp_sum <= 0){
                temp_sum = 0;
            }
            index++;
        }
        return max_sum;
    }
};


你可能感兴趣的:(array)