Continuous Subarray Sum II

Given an integer array, find a continuous rotate subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number. (If their are duplicate answer, return anyone. The answer can be rorate array or non- rorate array)

Have you met this question in a real interview? 
Yes
Example

Give [3, 1, -100, -3, 4], return [4,1].

這題與Continuous Subarray Sum的區別在與,由於變成了環,這樣起點就是不確定了的,所以問題變成了如何找起點能夠使得環得到最大的聯繫字串和;說先想到的是暴力解,遍歷所有的可能的起點,然後得到最大值的起點,再按照Continuous Subarray Sum的方式求解起始點位置,這樣的時間複雜度爲O(N^2);那麼如何優化,讓其可以達到O(N)的時間複雜度;這裏要用到連續最小子串的概念,如果可以求出在原數組中,連續最小字串的最後一個點的下標值爲minIndex,假如,以minIndex前的點爲起點,由於其要經過最小字串區間,所以其值必然不會達到最終的最大,因此,要使字串能夠儘可能的大,那麼其起點應該從minIndex開始;有了這樣的分析之後代碼自然就好寫了。

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) {
        // Write your code here
        vector<int> ans;
        int len = A.size();
        if(len < 1)
            return ans;
        if(len == 1)
        {
            ans.push_back(0);
            ans.push_back(0);
            return ans;
        }
        
        int Min = INT_MAX, minIndex = 0, curMin = A[0];
        for(int i = 1; i < len; ++i)
        {
            curMin = min(curMin + A[i], A[i]);
            if(curMin < Min)
            {
                Min = curMin;
                minIndex = i;
            }
        }
        
        
        int index = (minIndex + 1) % len, Max = Min, high = minIndex, curMax = Min;
        while(index != minIndex)
        {
            curMax = max(curMax + A[index], A[index]);
            if(Max < curMax)
            {
                Max = curMax;
                high = index;
            }
            index = (index + 1) % len;
        }
        
        int low = high, tmpMax = Max;
        while(tmpMax)
        {
            tmpMax -= A[low];
            low = (low - 1 + len) % len;
        }
        
        ans.push_back((low + 1) % len);
        ans.push_back(high);
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章