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;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值