## CSDN博客

### 最大子序列和问题的思考

/*
* 问题描述：
* 最大的子序列和问题：给定整数A1, A2, ....AN (可能有负数)，
*      求Ak到Aj的最大和值k--j是连续的
*      可以给出线性的算法(看MaxSubsequenceSum2.cpp)
*/
#include <stdio.h>

#define  NUM 8

void main( void )
{
//
// set the number
//
int source[NUM];

for (int client = 0; client < NUM; client++)
scanf("%d", &source[client]);
//
// get the maxSubSequenceSum
//
int maxSum = 0;
int clientSum = 0;

for (client = 0; client < NUM; client++)
{
for (int temp = client; temp < NUM; temp++)
{
clientSum += source[temp];
if (clientSum > maxSum)
{
maxSum = clientSum;
}
}
clientSum = 0;
}
printf("/n%d/n", maxSum);
}

/*
* 问题描述：
* 最大的子序列和问题：给定整数A1, A2, ....An (可能有负数)，
*      求Ak到Aj的最大和值k--j是连续的
*      MaxSubsequenceSum2.cpp
*/
#include <stdio.h>

#define  NUM 8

void main( void )
{
//
// set the number
//
int source[NUM];

for (int client = 0; client < NUM; client++)
scanf("%d", &source[client]);
//
// get the maxSubSequenceSum
//
int maxSum = 0;
int clientSum = 0;

for (client = 0; client < NUM; client++)
{
clientSum  +=  source[temp];
if (clientSum > maxSum)
maxSum = clientSum;
else if( clientSum < 0)//将丢掉左边的全部
clientSum = 0;
printf("/n%d/n", maxSum);
}

0 0