LintCode "Continuous Subarray Sum II"

來源:互聯網
上載者:User

標籤:

Flip over your mind: in rotated subarray case, we can simply cut the continuous smallest subarray.

class Solution {public:    /**     * @param A an integer array     * @return  A list of integers includes the index of     *          the first number and the index of the last number     */    vector<int> continuousSubarraySumII(vector<int>& A) {        vector<int> ret;        size_t len = A.size();        long long sum = A[0], csum = A[0];        int s = 0, e = 0, ss = 0, ee = 0; // for max continuous        long long sum0= A[0], csum0= A[0];        int s0= 0, e0= 0, ss0= 0, ee0= 0; // for min continuous        bool bAllNeg = true;        for (int i = 1; i < len; i++)        {            if(A[i] >= 0) bAllNeg = false;            //  max            long long nsum = csum + A[i];            if (A[i] > nsum)            {                ss = ee = i;                csum = A[i];            }            else            {                ee = i;                csum = nsum;            }             if(csum > sum)            {                sum = csum;                s = ss;                e = ee;            }            //  min            long long nsum0 = csum0 + A[i];            if (A[i] < nsum0)            {                ss0 = ee0 = i;                csum0= A[i];            }            else            {                ee0 = i;                csum0= nsum0;            }            if(csum0 < sum0)            {                sum0 = csum0;                s0 = ss0;                e0 = ee0;            }        }        long long asum = accumulate(A.begin(), A.end(), 0);        long long osum = asum - sum0;        if (bAllNeg)        {            int inx = max_element(A.begin(), A.end()) - A.begin();            ret.push_back(inx);            ret.push_back(inx);        }        else if (sum >= osum)        {            ret.push_back(s);            ret.push_back(e);        }        else        {            ret.push_back(e0 + 1);            ret.push_back(s0 - 1);        }        return ret;    }};

LintCode "Continuous Subarray Sum II"

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.