【问题标题】:Algorithm to return the maximum possible sum of subsequences in a sequence返回序列中子序列的最大可能和的算法
【发布时间】:2009-03-08 23:26:03
【问题描述】:
int maxSumRec(const vector<int> &a, int left, int right){

    if (left == right){

               if (a[left] > 0){
        return a[left];
               }
               else
                  return 0;

    }

    int center = (left + right)/2;
    int maxLeftSum = maxSumRec(a, left, center);
    int maxRightSum = maxSumRec(a, center+1, right);

    int leftBorderSum = 0; int leftBorderMax = 0; 
    for (int i = center; i >= left; i--){

        leftBorderSum += a[i];
        if (leftBorderSum > leftBorderMax){

            leftBorderMax = leftBorderSum;
        }
    }

    int rightBorderSum = 0; int rightBorderMax = 0;
    for (int i = center+1; i <= right; i++){

        rightBorderSum += a[i];
        if (rightBorderSum > rightBorderMax){

            rightBorderMax = rightBorderSum;
        }

    }

    int crossSum = rightBorderMax + leftBorderMax;

    return max3(maxLeftSum, maxRightSum, crossSum);

}

这是一个 O(NlogN) 算法,我知道它不是最好的。但只是有几个问题:

  1. 在第一个if语句中,为什么a[left]

  2. 为什么需要 2 个 for 循环?不是这样的逻辑吗,求前半部分和后半部分的最大值,然后相加,看相加是否大于两者。 如果是这种情况,那我们可以直接跳到最后2行吗?

非常感谢,

悦哈丽特

【问题讨论】:

  • 这是一个项目欧拉问题吗?

标签: c++ algorithm


【解决方案1】:
  1. 在第一个if语句中,为什么a[left]

因为此时空子序列的和最大,为0。

【讨论】:

    【解决方案2】:

    好的,我想出了第二个问题,因为我们必须注意连续词而不是跳跃词。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多