leetcode53 C++ 12ms/8ms 最大子序列和 百度面试题 两种解法

#include <climits>

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int curr = 0;
        int res = INT_MIN;
        for(int i=0; i<nums.size();i++){
            if(curr<0){
                curr = 0;
            }
            curr += nums[i];
            res = res> curr? res: curr;
        }
        return res;
    }
};

class Solution {
public:

    int maxSubArray(vector<int>& nums) {

        vector<int>::iterator it  = nums.begin();
        int maxSum = *it;
        int theSum = *it;

        for(it = it+1 ; it != nums.end(); it++){
            theSum = (theSum + *it )> (*it) ? (theSum + *it ) : (*it);
            maxSum = maxSum > theSum ? maxSum: theSum;
        }

        return maxSum;
    }
};

posted @ 2018-08-02 17:18  一条图图犬  阅读(135)  评论(0编辑  收藏  举报