zoukankan      html  css  js  c++  java
  • LintCode "Continuous Subarray Sum II"

    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;
        }
    };
  • 相关阅读:
    Perface(TCP/IP 协议族)
    CHAPTER 2 Database Environment
    Chapter 1 Introduction
    2. Instructions: Language of the computer (指令:计算机语言)
    sed命令
    磁盘配额
    外设,镜像
    磁盘及文件系统挂载
    网络客户端工具命令
    TCP协议
  • 原文地址:https://www.cnblogs.com/tonix/p/4851788.html
Copyright © 2011-2022 走看看