LeetCode53 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        //int sum=nums[0];
        //int n=nums[0];
        //for(int i=1;i
            //if(n>0)n+=nums[i];
            //else n=nums[i];
            //if(sum
       // }
        //return sum;
        if(nums.size()==0)
            return 0;
        vector<int> nums1,nums2;
        int SUM = nums[0], sum1 = 0, sum2 = 0;
        vector<int>::iterator iter1,iter2,iter3;
        for(iter1 = nums.begin(); iter1 != nums.end(); ++iter1)
        {
            if(*iter1 > 0)
            {
                for(iter2 = iter1; iter2 != nums.end(); ++iter2,sum2 = 0)
                {
                    if(*iter2 >= 0)
                    {
                        nums1.push_back(*iter2);
                        nums2.push_back(*iter2);
                        sum1 += *iter2;
                        iter1 = iter2;
                        continue;                        
                    }
                    else if((sum1 + *iter2)>0)
                    {
                        if(1)
                        {
                            bool end = false;
                            for(iter3 = iter2; iter3 != nums.end(); ++iter3)
                            {
                                nums2.push_back(*iter3);
                                sum2 += *iter3;
                                if(sum2 > 0)
                                {
                                    nums1 = nums2;
                                    iter1 = iter3;
                                    iter2 = iter3;
                                    sum1 += sum2;
                                    end = true;
                                    break;
                                }
                                if(sum1+sum2 < 0)
                                    break;
                            }
                            if(end)
                                continue;
                        }
                        SUM = (SUM > sum1)?SUM:sum1;
                        sum1 = 0;
                        sum2 = 0;
                        iter1 = iter2-1;
                        break;
                    }
                    else
                    {
                        SUM = (SUM > sum1)?SUM:sum1;
                        sum1 = 0;
                        iter1 = iter2-1;
                        break;
                    }
                }
                SUM = (SUM > sum1)?SUM:sum1;
            }
            else
            {
                SUM = (SUM >= *iter1)?SUM:*iter1;
            }

        }
        return SUM;

    }
};

你可能感兴趣的:(#,LEETCODE)