最大(最小)连续子序列之和----并求出序列的起始下标

 算法:

struct Seq{
    int sum;
    int startIndex;
    int endIndex;
};

Seq maxSubSum4(const vector<int> & a)
{
    int thisSum = 0;
    int startIndex =0;
    int temp = 0;
    int endIndex = 0;
    int maxSum = a[0];
    for(int j=0;j<a.size();j++){// //如果序列全为负数,直接找最大的负数
        if(maxSum < a[j]){
            maxSum = a[j];
            endIndex = j;
            startIndex = endIndex;
        }
    }
    if(maxSum >0){//序列为正负数(且maxSum大于0)或者全是正数
        for(int j=0;j<a.size();j++){
            if(thisSum<0){ //需要丢弃此序列,重新寻找新的连续序列,负数加任何数都是副作用
                thisSum = 0;
                temp = j;
            }

            thisSum+=a[j];    //Sum(i, j+1) = Sum(i, j) + A[j+1]

            if(thisSum > maxSum){
                maxSum = thisSum;
                startIndex = temp;//新的开始,也就是起始坐标
                endIndex = j;
            }
        }
    }

    Seq maxSeq;
    maxSeq.sum = maxSum;
    maxSeq.startIndex = startIndex;
    maxSeq.endIndex = endIndex;

    return maxSeq;
}


Seq minSubSum4(const vector<int> & a)
{
    int thisSum = 0;
    int startIndex =0;
    int temp = 0;
    int endIndex = 0;
    int minSum = a[0];
    for(int j=0;j<a.size();j++){// //如果序列全为正数,直接找最大的正数
        if(minSum > a[j]){
            minSum = a[j];
            endIndex = j;
            startIndex = endIndex;
        }
    }
    if(minSum < 0){//序列为正负数(且minSum小于0)或者全是负数
        for(int j=0;j<a.size();j++){
            if(thisSum > 0){
                thisSum = 0;
                temp = j; //新的开始,也就是起始坐标
            }

            thisSum+=a[j];    //Sum(i, j+1) = Sum(i, j) + A[j+1]

            if(thisSum < minSum){
                minSum = thisSum;
                startIndex = temp;
                endIndex = j;
            }
        }
    }

    Seq minSeq;
    minSeq.sum = minSum;
    minSeq.startIndex = startIndex;
    minSeq.endIndex = endIndex;

    return minSeq;
}

测试

    vector<int> arr1 = {4,-1,5,-2,-1,2,6,-2,-1,5,-2,-1};
    vector<int> arr2 = {9,-3,-5,-7,11,7};
    vector<int> arr3 = {-3,-3,-7,-2,-5};
    vector<int> arr4 = {3,-2,5,-7,9,-6,-7,-3,2,10};
    vector<int> arr5 = {20,3,-10,2,-32,14,5,6,-7};

结果

最大子序列的和为 15  startIndex is 0  endIndex is 9  
最大子序列的和为 18  startIndex is 4  endIndex is 5  
最大子序列的和为 -2  startIndex is 3  endIndex is 3  
最大子序列的和为 12  startIndex is 8  endIndex is 9  
最大子序列的和为 25  startIndex is 5  endIndex is 7  
最小子序列的和为 -3  startIndex is 3  endIndex is 4  
最小子序列的和为 -15  startIndex is 1  endIndex is 3  
最小子序列的和为 -20  startIndex is 0  endIndex is 4  
最小子序列的和为 -16  startIndex is 5  endIndex is 7  
最小子序列的和为 -40  startIndex is 2  endIndex is 4  
按 <RETURN> 来关闭窗口...

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值