求最大子序列之和最小子序列之和、求最大乘积子序列都可以用动态规划方法处理。
求最小正子序列的方法则要用特殊的方法稍加处理。
#include <iostream>
#include <algorithm>
using namespace std;
//交换元素
void swap(int &num1, int &num2)
{
int tmp;
tmp = num1;
num1 = num2;
num2 = tmp;
}
//求最大子序列之和
int maxSubsequence(const int A[], int N)
{
int thisSum, maxSum, j;
thisSum = maxSum = 0;
for (j = 0; j < N; j++)
{
thisSum += A[j];
if (thisSum > maxSum)
maxSum = thisSum;
else if (thisSum < 0)
thisSum = 0;
}
return maxSum;
}
//求最小子序列之和
int minSubsequence(const int A[], int N)
{
int thisSum, minSum, j;
thisSum = minSum = 0;
for (j = 0; j < N