max sub_sequence - c
/*
problem:
there is a sequence of number,could be positive or negative,
find out the sub sequence which has max sum,
solution:
loop the sequence,
use maxendinghere to record sum of elements,when sum < 0, set to 0 and go on summation from next element,
use maxsofar to record the max sum, each time there is a new maxendinghere, compare with it, and update maxsofar if nessary,
use a struct seq_max_result to record the result, which include sum / start / end,
efficiency:
time is O(n), every efficient,
memory is O(1),
*/
#include <stdio.h>
typedef struct {
int sum,start,end;
} seq_max_result;
seq_max_result * seq_max(int *arr,int len) {
// start is the start of every maxendinghere
int maxsofar = 0,maxendinghere=0,i=0,start=0;
static seq_max_result result = {0,0,0};
for(i=0;i<len;i++) {
if(maxendinghere+*(arr+i) < 0) {
maxendinghere = 0;
start = i+1;
} else {
maxendinghere += *(arr+i);
}
if(maxsofar<maxendinghere) {
maxsofar = maxendinghere;
result.start = start;
result.end = i;
}
}
result.sum = maxsofar;
return &result;
}
int main() {
int arr[10] = {-6,2,7,9,-5,6,9,-10,3,5};
seq_max_result *result = seq_max(arr,10);
result = seq_max(arr,10);
printf("[%d , %d]: %d\n",result->start,result->end,result->sum);
}
最大子序列和算法

本文介绍了一种寻找具有最大和的子序列的高效算法。该算法通过遍历序列并使用maxendinghere记录局部最大值,maxsofar记录全局最大值来工作。在遍历过程中,当maxendinghere小于0时将其置0并重新开始计数;否则继续累加。最终返回包含最大子序列起始位置、结束位置及总和的结构体。

被折叠的 条评论
为什么被折叠?



