最大子数组和

#include <iostream>

using namespace std;

int Find_Max_Crossing_SubAr(int A[], int low, int mid, int high,int *max_left,int *max_right)
{

   int left_sum = -10000000;
   int sum = 0;
   for (int i = mid; i >= low; i --)
   {
      sum += A[i];
      if (sum >left_sum)
      {
         left_sum = sum;
         *max_left=i;

      }
   }
   int right_sum = -100000000;
   sum = 0;
   for (int j = mid + 1; j <= high; j ++)
   {
      sum += A[j];
      if (sum > right_sum)
      {
         right_sum = sum;
         *max_right=j;
      }
   }
   return left_sum + right_sum;
}

int Find_Maximum_SubAr(int A[], int low, int high,int *max_left,int *max_right)
{
   int left_sum, right_sum, cross_sum;
   if (high == low)
   {
      *max_left=low;
      *max_right=high;
      return A[low];
   }
   else
   {
      int mid = (low + high) / 2;
      left_sum = Find_Maximum_SubAr(A, low, mid,max_left,max_right);
      right_sum = Find_Maximum_SubAr(A, mid + 1, high,max_left,max_right);
      cross_sum = Find_Max_Crossing_SubAr(A, low, mid, high,max_left,max_right);
      if (left_sum >= right_sum && left_sum >= cross_sum)
      {
         return left_sum;
      }
      else if (right_sum >= left_sum && right_sum >= cross_sum)
      {
         return right_sum;
      }
      else
      {
         return cross_sum;
      }
   }
}
int main()
{
    int A[100];
    int n;
    cout<<"Input the number of numbers:";
    cin>>n;
    for (int i = 0; i < n; i ++)
    {
       cin>>A[i];
    }
    int s,l;
    cout<<"The max sum of the subarray is:"<<Find_Maximum_SubAr(A, 0, n - 1,&s,&l)<<endl;
    s=s+1;l=l+1;
    cout<<"from "<<s<<" to "<<l<<endl;
    return 0;
}

该算法复杂度O(n*logn);

主要思想:最大子数组区间必定存在于数组中点左方(不包括中点处)或跨越中点或数组中点右方(不包括中点)的区域,再使用递归便可求出。

点赞