查找具有最大和的连续子数组

Finding the contiguous sub array with max sum

本文关键字:连续 数组 和的 查找      更新时间:2023-10-16

这是我从给定数组中查找子数组(连续)的最大和的程序。使用kadane的算法非常简单。

#include <iostream>
#include <cstdio>
using namespace std;
int kadane(int a[], int n) {
    int max_ending_here = a[0], max_till_now = a[0];
    int _start = 0, _end;
    bool s=true;
    for (int i = 1; i < n; ++i)
    {
        max_ending_here = max(a[i], max_ending_here + a[i]);
        if(max_ending_here + a[i] > a[i] && s==false) _start = i, s=true;
        max_till_now = max(max_ending_here, max_till_now);
        if(max_ending_here + a[i] < a[i] && s==true) _end=i-1,s=false;
    }
     printf("S = %d , E = %dn",_start,_end);
    return max_till_now;
}
int main(int argc, char const *argv[])
{
    //int a[10] = {1,-3,2,-5,7,6,-1,-4,11,-23};
    int a[6] = {-8,-1,-1,-1,-1,-5};
    int m = kadane(a, 6);
    printf("%dn",m);
    return 0;
}

,但我也想找到具有最大和的连续子数组的开始和结束位置。我试着在上面的程序中添加几行来做到这一点,但它不起作用。我的问题是如何让子数组的起始和结束位置具有最大值?谢谢。

这样扩展函数签名:

int kadane(int a[], int n, int *start, int *end)

在函数末尾,在返回之前,像这样设置两个形参:

    *start = _start;
    *end = _end;
    return max_till_now;
}

然后这样命名:

int start, end;  
int m = kadane(a, 6, &start, &end);
printf("sum: %i, start %i, end: %in",m, *start, *end);

尝试使用此代码作为执行所需操作的基础。忽略葡萄牙语(我的母语)中的一些单词。

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void seg_max(int *v, int n, int & x, int &y , int & max){
 int i,j;
 int soma; 
 max = -1; 
 for(i=0;i<n;i++){
  soma = 0;
  for(j=i;j<n;j++){
   soma += v[j];
   if( soma > max ){
    max = soma;
    x = i;
    y = j;
   }
  }
 }
}
int main(){
int x,y,max;
int v[] = {-2,1,-3,4,-1,2,1,-5,4};
seg_max(v,9,x,y,max);
printf("max sum [%d-%d] with the sum equal to %dn", x,y,max);
}

要传递更多的函数,可以使用指针。下面应该可以了。

#include <cstdio>
using namespace std;
int kadane(int a[], int n, int* start, int* end ) {
    int max_ending_here = a[0], max_till_now = a[0];
    bool s=true;
    for (int i = 1; i < n; ++i)
    {
        max_ending_here = max(a[i], max_ending_here + a[i]);
        if(max_ending_here + a[i] > a[i] && s==false) {
             *start = i;
             s=true;
        }
        max_till_now = max(max_ending_here, max_till_now);
        if(max_ending_here + a[i] < a[i] && s==true) {
            *end = i-1;
            s = false;
        }
    }
    return max_till_now;
}
int main(int argc, char const *argv[])
{
    //int a[10] = {1,-3,2,-5,7,6,-1,-4,11,-23};
    int a[6] = {-8,-1,-1,-1,-1,-5};
    int start = 0, end = 0;
    int m = kadane(a, 6, &start, &end);
    printf("Max: %d, Start: %d, End: %dn",m, start, end);
    return 0;
}