Lintcode 41. Maximum Subarray

Description: Given an array of integers, find a contiguous subarray which has the largest sum.
Example: Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.
Challenge: Can you do it in time complexity O(n)?

My direct , idiotic,and complex solution. 100% test AC. All Rights Reserved.

Considering neighbored numbers with same sgn.

    int maxSubArray(vector<int> &nums) {
        // write your code here
        int maxval=nums[0];
        int sum2=0, i=0, len = nums.size();
        vector<int> record;
        int ind_beg = 0;
        while (ind_beg<len && nums[ind_beg] < 0) {
            if (nums[ind_beg]>maxval) 
                maxval = nums[ind_beg];
            ind_beg++;
        } 
        if (ind_beg == len)
            return maxval; // if there is no positive number in the array
        sum2 += nums[ind_beg];
        maxval = nums[ind_beg];
        for (i = ind_beg+1; i < len; i++) {
            if (nums[i]>maxval)  maxval = nums[i];
            if (nums[i] < 0) {
                int judge1 = nums[i++];
                while (i<len && nums[i] < 0) judge1 += nums[i++];
                if (i == len) {
                    record.push_back(sum2);
                    break;
                }
                int judge2 = nums[i++];
                while (i<len && nums[i]>=0) judge2 += nums[i++];
                if (judge1+sum2<=0) {
                    record.push_back(sum2);
                    sum2 = judge2;
                }
                else {
                    if (judge1 + judge2 >= 0) 
                        sum2 += judge1 + judge2;
                    else {
                        record.push_back(sum2);
                        sum2 += judge1 + judge2;
                    }
    
                }
                if (i == len) {
                    record.push_back(sum2);
                    break;
                }
                i--;
            }
            else 
                sum2 += nums[i];
        }
        record.push_back(sum2);
        record.push_back(maxval);  // if there is only one positive value
        int sub_seq = record.size();
        int best = record[0];
        for (i = 1; i<sub_seq; i++) {
            if (record[i]>best)
                best = record[i];
        }
        return best;
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 原题 LintCode 41. Maximum Subarray Description Given an arr...
    Andiedie阅读 252评论 0 0
  • 不但是这群侍从手下,连正在小院内的弃湖君也受到了影响。 而东伯雪鹰身后庞大的朱魇神鸟扇动着羽翼,下方的这座宫殿的镇...
    im喵小姐阅读 419评论 0 0
  • 1 从小我就很焦虑自己找不到工作,或者做不好工作。 焦虑到什么程度呢? 就是陪妈妈到银行办事,看到柜台的阿姨刷刷刷...
    清风少华阅读 335评论 0 0
  • 家有玫瑰红如血, 热情似火爱不绝。 送人玫瑰手留香, 你若喜欢成新娘。
    东方侠影阅读 252评论 0 15